gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:16:11 25 4
gpt4 key购买 nike

这段代码应该逐行读取文件,抓取它需要的数据,然后将其放入 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com