我正在逐行解析数据文件(包含json数据)并创建对象。然后,将这些对象添加到我在外部声明的数组中。但是由于某种原因,我的“服务”数组在linereader.on函数之外再次变空。我能够在linereader.on内进行console.log(services)并看到它按预期方式打印数据。但是我不知道为什么外面又变空了!
const getLineReader = function () {
return require('readline').createInterface({
input: require('fs').createReadStream('data.txt')
});
};
const getSystem = function () {
const lineReader = getLineReader();
const services = [];
lineReader.on('line', function (line) {
const serviceJSON = JSON.parse(line);
const tests = serviceJSON.tests.map(test => {
return new ServiceTest(
test.id,
test.name,
test.criticality);
});
const service = new NewService(new UniqueID(), serviceJSON.name, tests, new Timestamp());
services.push(service);
console.log(services); // prints Services { _services: [relevant data here] }
});
console.log(services); // prints Services { _services: [] }
最佳答案
您需要监听readline
'close'
事件,然后打印阵列。读取所有行后,将调用close
。
lineReader.on('close', function() {
console.log(services)
});
然后,您将得到如下结果:
const getSystem = function () {
const lineReader = getLineReader();
const services = [];
lineReader.on('line', function (line) {
const serviceJSON = JSON.parse(line);
const tests = serviceJSON.tests.map(test => {
return new ServiceTest(
test.id,
test.name,
test.criticality);
});
const service = new NewService(new UniqueID(), serviceJSON.name, tests, new Timestamp());
services.push(service);
console.log(services); // prints Services { _services: [relevant data here] }
});
lineReader.on('close', function() {
console.log(services)
});
}
在您当前的代码中,
console.log(services)
将在行lineReader.on('line', ...)
的代码之前触发。