javascript - Node JS 关闭一个读取流
问题描述
我坚持关闭读取流。我正在使用 csv-parser 模块从 CSV 文件中读取数据,进行一些处理并将数据写入 MongoDB。一切正常,除了我无法退出我的程序。它只是等待,我必须强制退出它。我怎样才能完成它的执行?
const main = () => {
const records = [];
fs.readdir(dataPath, (err, files) => {
if (err) console.log("Failed to read. ", err);
else {
fs.createReadStream(`${dataPath}/${files[0]}`)
.pipe(csv({ skipLines: 7, mapHeaders: ({ header, index }) => _.camelCase(header) }))
.on("data", data => records.push(data))
.on("end", async () => await saveToDB(getSysInfo(files[0]), records));
}
});
};
main();
我尝试.on("close")
在结束后添加一个事件,但这也无济于事。
解决方案
Here's an enhancement on your answer that adds error handling for the readStream and for the two await
operations so if there are any errors your program can still end in a controlled fashion and properly close the database:
const getRecordsFromFile = fileName => {
return new Promise((resolve, reject) => {
const rows = [];
fs.createReadStream(fileName)
.pipe(csv({ skipLines: 7, mapHeaders: ({ header, index }) => _.camelCase(header) }))
.on("data", row => rows.push(row))
.on("end", () => resolve(rows));
.on("error", reject); // <==
});
};
const main = async () => {
const files = fs.readdirSync(dataPath);
try {
for (let i = 0; i < files.length; i++) {
const records = await getRecordsFromFile(`${dataPath}/${files[i]}`);
await loadRecordsToDB(getSysInfo(files[i]), records);
}
} catch(e) { // <==
console.log(e); // <==
} finally { // <==
// make sure we always close the connection
mongoose.connection.close();
}
};
main();
推荐阅读
- tensorflow - val_loss 没有从 inf 改善
- javascript - 在Javascript中使用自定义增量生成从0到N的数组
- javascript - 无法在 Angular 中使用 drop 事件收集文件
- amazon-web-services - 无法从 EC2 实例访问 AWS 域控制器
- kubernetes - Spring Cloud Data Flow - 使用 Spring Cloud Kubernetes Deployer 的分区批处理作业:环境属性未传递给工作线程
- reactjs - 为 React 组件编写单元测试
- python - 从网址中间删除表达式
- powershell - 根据文件夹中的文件移动文件夹
- java - 检索 SafetyNet 令牌时出现问题:7:firebase OTP
- python - 如何检查字符串是否仅包含 Python 中字母列表中的字母