zyxue zyxue - 4 months ago 10
Node.js Question

javascript reading data results in an empty object

I have the following code:

var lineReader = require('readline').createInterface({
input: require('fs').createReadStream('graph.txt')
});

var graph = {};

lineReader.on('line', function (line) {
var spl = line.split('\t');
graph[spl[0]] = spl.slice(1);
});

console.log(graph);


graph.txt
contains data representing a graph in adjacency lists such as

1 3 2 3
2 1 3
3 1 2 1


I ran the code with
node script.js
. I don't understand why at the end
graph
is still an empty object. What's the correct way to read data into an object?

Answer

Try replacing the console.log(graph); call with:

lineReader.on('close', function () {
    console.log(graph);
});

You see the empty object because your log happens before the file is read, as reading is async.