node.js - 为什么 fast-csv 不将数据存储在 NodeJS 中?
问题描述
您好,我只想在节点中存储一列 CSV 以操作数组中的数据,我正在尝试读取并存储它,但它不起作用发生了什么?这是我的代码
let stream = fs.createReadStream("Supliers.csv");
let csvStream = csv({headers: true})
.on("data", function(data){
/*data.forEach(x => {
console.log(x)
})*/
Final.push(data)
})
.on("end", function(){
console.log(Final);//[THE COMPLETE DATA TOTALLY OK]
});
stream.pipe(csvStream);
console.log(Final)// []
我不明白:(帮助
解决方案
根据您的代码,我添加了注释。
let stream = fs.createReadStream("Supliers.csv");
let csvStream = csv({headers: true}).on("data", function(data){
// This is inside a function that gets slightly later, in the
// next tick of the event loop. I.e. it's called after
// the 'console.log(Final)' statement.
Final.push(data)
})
.on("end", function(){
// You can do your processing in this function
console.log(Final);
});
stream.pipe(csvStream);
// This gets called before the '.on("data"...' function.
console.log(Final)
// To prove that this works (***but don't use this in your code***)
// the following should work too.
setTimeout(() => console.log(Final), 100);
我推荐阅读 Node.js 事件循环:https ://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/
推荐阅读
- java - 以编程方式修改 Xtext 生成的 Mwe2 工作流
- knockout.js - Magento2 在 Minicart 上调用静态图像
- java - SpringBootApplication 不会自动装配我的服务
- python - 条形图月份与其累积值的对比
- python-3.x - 用Python擦除关键字定义范围内的一些文件行
- java - 如何从 2 个数组中获取每个值的差异
- python - scipy.optimize.minimize 相同(?)输入的两个不同输出
- javascript - 反应原生 - 在 for 循环中一个接一个地打开多个模式
- performance - 对一个非常大的 SQL 表进行简单的 UPDATE 查询
- vim - VIM:命令行模式下的单词完成?