egilchri
egilchri

Reputation: 761

Nodejs read file line by line and accumulate results in global object

Classic embarrassing newbie question. Why doesn't my store variable contain any results? I know it is accumulating results along the way. I also know enough about nodejs to know it has to do with promises, single-threadedness, etc.

var readline = require('readline');
var fs = require("fs");

var pathToFile = '/scratch/myData.csv';

var rd = readline.createInterface({
    input: fs.createReadStream(pathToFile),
    // output: process.stdout,
    console: false
});

var store = {};
rd.on('line', function(line) {
    store[line] = 1;
    // console.log (`store is now: ${JSON.stringify (store)}`);
});

console.log (`store is now: ${JSON.stringify (store)}`);

Upvotes: 0

Views: 70

Answers (1)

Shimon Brandsdorfer
Shimon Brandsdorfer

Reputation: 1723

This has nothing to do with Promises, (Although, you can promisify it, if you like).

As you said, it is accumulating the results line by line, but this is hapening inside the scope of the callback function. And if you want to make use of the data, you will have to call another function inside the callback function when the last line is called, (or maybe listen to a different event).

Something like the following:

var store = {};
rd.on('line', function(line) {
    store[line] = 1;
    // console.log (`store is now: ${JSON.stringify (store)}`);
})
.on('close', function() {
    myFunc(store);
});

function myFunc(store){
   console.log (`store is now: ${JSON.stringify (store)}`);
}

Upvotes: 1

Related Questions