The Changes I'm Making To My Array Inside Linereader.on Are Not Available Outside
I'm parsing a data file (which contains json data) line-by-line and creating objects. I then add these objects to an array which I have declared outside. But for some reason, my 's
Solution 1:
You need to listen to the readline
'close'
event and then print the array. close
will be called once all lines have been read.
lineReader.on('close', function() {
console.log(services)
});
You'll then end up with something like:
const getSystem = function () {
const lineReader = getLineReader();
const services = [];
lineReader.on('line', function (line) {
const serviceJSON = JSON.parse(line);
const tests = serviceJSON.tests.map(test => {
returnnewServiceTest(
test.id,
test.name,
test.criticality);
});
const service = newNewService(newUniqueID(), serviceJSON.name, tests, newTimestamp());
services.push(service);
console.log(services); // prints Services { _services: [relevant data here] }
});
lineReader.on('close', function() {
console.log(services)
});
}
In your current code, console.log(services)
will fire before the line lineReader.on('line', ...)
code.
Post a Comment for "The Changes I'm Making To My Array Inside Linereader.on Are Not Available Outside"