如何确保 lineReader 完成 运行 并在打印数组之前填充数组

How can I ensure the lineReader has finished running and populating the array before printing the array after

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

    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

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)
})