简体   繁体   English

createReadStream 的同步

[英]Synchronisation of createReadStream

I'm very noob at Javascript.我对 Javascript 非常陌生。 All I'm trying to do is read a CSV file from local and playaround with the data, like converting the rows into arrays of array.我要做的就是从本地读取 CSV 文件并使用数据进行处理,例如将行转换为数组的 arrays。 I came across the fs.createReadStream , which helps to read csv data but I'm unable to utilize the processed csv data later.我遇到了fs.createReadStream ,它有助于读取 csv 数据,但稍后我无法使用处理过的 csv 数据。 I read in some thread, and I guess the issue with the synchronisation.我读了一些帖子,我猜是同步的问题。 My code looks like this-我的代码看起来像这样-

ar abc = [] 
const csv = require('csv-parser');
const fs = require('fs');

fs.createReadStream('data.csv')
  .pipe(csv())
  .on('data', (row) => {
    var nums =[];

   // console.log(row);
    nums.push(row['time'])
    nums.push(row['return'])
    
    abc.push(nums)
    
  })
  .on('end', function () {
    console.log(abc)
      })
  

  var final_sort= []
  console.log()
  for (let i = 0; i < abc.length; i=i+5){

    final_sort.push(abc[i])


  } 
  console.log(final_sort)

this outputs log outside fs first then outputs the fs.createReadStream.这首先在 fs 之外输出日志,然后输出 fs.createReadStream。 I wanted the fs.我想要fs。 createReadStream to be processed first, then I can utilize the data further.首先处理 createReadStream,然后我可以进一步利用数据。

if you want to handle your sequence then you have to try promises如果你想处理你的序列,那么你必须尝试承诺

if your task is read all data and then sort then your code will be like如果您的任务是读取所有数据然后排序,那么您的代码将类似于

var abc = []
const csv = require('csv-parser');
const fs = require('fs');
// -----------1 process start
await new Promise((resolve, reject) => {
  fs.createReadStream('data.csv')
    .pipe(csv())
    .on('data', (row) => {
      var nums = [];

      // console.log(row);
      nums.push(row['time'])
      nums.push(row['return'])

      abc.push(nums)

    })
    .on('end', function () {
      console.log(abc)
      //---------- 2 return after all data read
      resolve()
    })
});
//---------- 3 here you get all data
var final_sort = []
console.log()
for (let i = 0; i < abc.length; i = i + 5) {

  final_sort.push(abc[i])


}
console.log(final_sort)

for more refenerce understanding-javascript-promises更多参考理解-javascript-promises

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

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