【问题标题】:How can I ensure the lineReader has finished running and populating the array before printing the array after如何确保 lineReader 在打印数组之前完成运行并填充数组
【发布时间】:2019-09-23 15:11:24
【问题描述】:

此代码应该逐行读取文件,获取所需的数据,然后将其放入 timeStamps 数组中。虽然它确实将数据放入数组中,但它会继续通过该函数并在行阅读器填充它之前打印一个空数组。我知道它会填充数组,因为我可以添加 5 秒的超时,然后它会打印出整个数组。如何实现异步函数并等待 linereader?

    const lineReader = require('readline').createInterface({
    input: require('fs').createReadStream('./data/test.json')
});

let timeStamps = [];

lineReader.on('line', (line) => {
    if (line.includes('timestampMs')) {
        timeStamps.push(line.toString().substring(21, 34))
        console.log(timeStamps) //prints array with each element added one by one
    }
});

console.log(timeStamps)//prints empty array

【问题讨论】:

    标签: arrays node.js readline fs


    【解决方案1】:

    linereader 完成后会发出 close 事件,因此应该会打印正确的结果:

    lineReader.on('close', () => {
        console.log(timeStamps); //Print this when you finish reading test.json
    });
    

    完整示例:

    const lineReader = require('readline').createInterface({
      input: require('fs').createReadStream('./data/test.json')
    });
    
    let timeStamps = [];
    
    lineReader.on('line', (line) => {
      if (line.includes('timestampMs')) {
        timeStamps.push(line.toString().substring(21, 34))
        console.log(timeStamps) //prints array with each element added one by one
      }
    });
    
    lineReader.on('close', () => {
      console.log(timeStamps)
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-16
      • 2021-09-29
      • 2021-12-29
      • 2019-01-21
      • 1970-01-01
      • 2020-11-25
      相关资源
      最近更新 更多