这段代码应该逐行读取文件,抓取它需要的数据,然后将其放入 timeStamps 数组中。虽然它确实将数据放入数组中,但它会继续经过该函数并在行读取器填充它之前打印一个空数组。我知道它会填充数组,因为我可以添加 5 秒的超时,然后它会打印出完整的数组。如何实现异步函数并等待行读取器?
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)
})
关于arrays - 在打印数组之前,如何确保 lineReader 已完成运行并填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55997466/