该代码应该逐行读取文件,获取所需的数据,然后将其放入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
最佳答案
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)
})