zyxue zyxue - 6 months ago 14
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);


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
is still an empty object. What's the correct way to read data into an object?


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

lineReader.on('close', function () {

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