简体   繁体   English

无法访问从 node.js ReadStream 存储的数据?

[英]Can't access data stored from a node.js ReadStream?

I've got this node.js file reading a .csv through a data stream like such:我有这个 node.js 文件通过这样的数据流读取 .csv:

shldata = []

fs.createReadStream('./spreadsheets/shl.csv')
.pipe(csv({separator:';'}))
.on('data', (row) => {
    shldata.push(row);
})
.on('end',() => {
    console.log('CSV file successfully processed');
});

console.log(shldata);

BTW I couldn't find another way to do this if not via a read stream.顺便说一句,如果不是通过读取流,我找不到另一种方法来做到这一点。

If I console.log the data inside the ".on('end')" promise, it gives me the data.如果我在“.on('end')”promise 中控制台.log 数据,它会给我数据。 If I do it afterwards, it gives me null.如果我之后再做,它会给我空值。

I get a feeling the stream gets queued and reads only after logging the data variable.我有一种感觉,流被排队,只有在记录数据变量后才读取。

I've tried adding "return shldata" to the promise to no avail.我试过在承诺中添加“返回 shldata”,但无济于事。

Also, I'm trying to delete some of the columns of the CSV that I won't need.另外,我正在尝试删除一些我不需要的 CSV 列。 I tried adding this for loop inside the promise:我尝试在承诺中添加这个 for 循环:

for (i=0; i < shldata.length; i++){
    delete shldata[i]['key1'];
    delete shldata[i]['key2'];
    (...)
}

It works, but only if I repeat that line for each column header.它有效,但前提是我为每个列标题重复该行。 If I try to use a key array like such, it doesn't work:如果我尝试使用这样的键数组,它不起作用:

for (i=0; i < shldata.length; i++){
    delete shldata[i][keystoRemove];
}

Where the array "keystoRemove" is set prior to the stream.在流之前设置数组“keystoRemove”。 I got a feeling that I need to input this array somehow into this promise, otherwise it won't read it.我有一种感觉,我需要以某种方式将这个数组输入到这个 promise 中,否则它不会读取它。

This all feels needlessly complicated.这一切都感觉不必要地复杂。 I'm just trying to write a script to read a few files, change their data a little bit and submit an HTTP post to an API.我只是想编写一个脚本来读取几个文件,稍微更改它们的数据并向 API 提交 HTTP 帖子。

You can access shldata in its entirety inside the 'end' event handler.您可以访问shldata在整体上“结束”事件处理

.on('end',() => {
    console.log('CSV file successfully processed');
    // at this point you have all the data.
}

Your current code is trying to access it before all the data's been processed and all the events have fired.您当前的代码正在尝试在处理所有数据和触发所有事件之前访问它。 You could, if this were a dedicated function, return shldata;如果这是一个专用函数,您可以return shldata; inside this event handler.在此事件处理程序中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM