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回答后更新代码.