I run the following script and it prints the output for every line in file, but I need output the answer once when done, not on every line. Anyone please help me
const fs = require("fs");
const readline = require("readline");
const stream = require("stream");
const filename = process.argv[2];
const instream = fs.createReadStream(filename);
const outstream = new stream();
outstream.readable = true;
outstream.writable = true;
const rl = readline.createInterface({
input: instream,
output: outstream,
terminal: false,
});
const obj = {};
rl.on("line", function (line) {
const [country] = line.split(",", 1);
{
for (let i = 0; i < [country].length; i++)
if (obj[country] != null) {
obj[country] += 1;
} else {
obj[country] = 1;
}
}
console.log(obj);
});
You can use close event, This event is called after the read stream is closed and has been processed.
rl.on("close", function (line) {
console.log(obj);
});