Newbie with node.js.
I have set up an Node/express server on a Windows Server hosting a PostgreSQL database.
My goal is to insert in the database the data from a csv file choosen by a user on its own computer, using a HTML form.

以下是用户提交表单后执行的js文件的一部分:

app.post('/envoi', upload.single("fichiercsv"), async(req, res) => {
let newClient
try {
    const { identifiant, motdepasse } = req.body
    const clientConfigModifie = {
    ...clientConfigDefaut,
    user: identifiant,
    password: ''
    }
    newClient = new Client(clientConfigModifie)
        
    await newClient.connect()
     
    const rows = []
    const buffer = req.file.buffer
        // console.log(buffer) //ok
    const readableStreamFromBuffer = new stream.Readable()
    readableStreamFromBuffer.push(req.file.buffer)
    readableStreamFromBuffer.push(null)
    await new Promise( (resolve, reject) => {
        fastcsv.parseStream(readableStreamFromBuffer, { headers: false })
            .on('data', us => {
                rows.push(us)   
            })
            .on('end', async() => { 
                rows.shift()
                const usTotal = rows.map( us => us.join("").split(";"))
                // console.log(us)
                for (const us of usTotal) {
                await newClient.query("insert into activite.us (numus, gidgeo) VALUES ($1, $2)", [us[0], us[13]])
                })
                resolve()
            })
            .on("error", error => console.error(error))
        })  
}   
catch(e) {
    console.log("erreur lors du traitement", e)
    res.send(`<h3>échec de la connexion</h3>`)
}
finally {
    try {
        newClient.end()
    }
    catch(e) { 
        console.log(e) 
    }
}
})
  • 如果省略finally部分,数据将插入到数据库中,但连接仍在运行...
  • 对于finally零件,只插入us的第first行.因此,我得到了这样的信息:

error: Connection terminated at C:\Apache\balbla\

In this case, it seems that newClient.query runs one time only then for some reason the connection is terminated but not ended.
What am I doing wrong ?

EDIT:@I2yscho回答后更新代码.

推荐答案

问题是您不能异步处理插入操作.此代码不是处理此问题的最佳方式,但它是有效的解决方案.我建议您在一个查询中使用某种大容量插入.

.on('end', () => {
            rows.shift();
            const usData = rows.map(us => us.join("").split(";"));
            
            const insertPromises = usData.map(us => {
                return newClient.query("INSERT INTO activite.us (numus, gidgeo) VALUES ($1, $2)", [us[0], us[13]]);
            });

            Promise.all(insertPromises)
                .then(() => {
                    resolve();
                })
                .catch(error => {
                    reject(error);
                });
        })

Node.js相关问答推荐

nest js控制器方法调用两次

Twilio-获取呼叫录音不起作用的请求

ForbidenError:使用Express.js的CSRF令牌无效

在 azure blob 容器之间复制文件

如何获取mongoose中单个id数据的记录

在nodejs中为oauth请求创建和存储csrf令牌的最佳方法

是否可以在 NodeJS 代码库中的每个函数之前和之后添加 console.log?

安装样式组件时出现react 错误

如何避免在 mongodb 聚合中查找重复结果?

Express.js cookie setter 的 Domain 属性:如何与 *多个 * 域共享 cookie?

在express js模型中将js转换为Typescript 时Typescript 错误

无法通过谷歌Electron 表格 api( node js)中的服务帐户访问写入

Sharp JS 依赖关系 destruct 了 Elastic Beanstalk 上的 Express Server

使用 WebSockets 有服务器成本吗?

我应该在(Docker)容器中使用 forever/pm2 吗?

如何让should.be.false语法通过 jslint?

从 React(同构应用程序)进行 API 调用时出现Access-Control-Allow-Origin问题

node.js 在控制台上显示未定义

Nodejs将字符串转换为UTF-8

Puppeteer 等待所有图像加载然后截图