【问题标题】:Why fast-csv doesn't store the data in NodeJS ?为什么 fast-csv 不将数据存储在 NodeJS 中?
【发布时间】:2018-07-12 02:06:07
【问题描述】:

您好,我只想在节点中存储一列 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)// []

我不明白:(帮助

【问题讨论】:

    标签: node.js file csv


    【解决方案1】:

    根据你的代码,我添加了 cmets。

    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/

    【讨论】:

    • 我可以做些什么来存储数据以在另一个函数中使用它?感谢您的回答
    • 这取决于你想用它做什么。您可以将必要的代码放在.on("end"... 函数中。这是处理数据的好地方。
    • 我会试试@psiphi75 谢谢
    猜你喜欢
    • 2021-09-07
    • 1970-01-01
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多