-1

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?

zyxue
  • 7,904
  • 5
  • 48
  • 74
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – XCS Jul 25 '16 at 21:30
  • 1
    Readline is running asynchronously, that's why your `console.log(graph)` at the end of the program is empty – Commodore Timo Jul 25 '16 at 21:34
  • I will refer myself to this thread: http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron, One word answer: **asynchronicity** – zyxue Jul 25 '16 at 21:34
  • 1
    The console.log(graph) runs before the lineReader.on() call finishes. – Duly Kinsky Jul 25 '16 at 21:39

2 Answers2

2

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.

XCS
  • 27,244
  • 26
  • 101
  • 151
1

What you have there is some asynchronous code which you expect to be called completely synchroonously. First, you open the file, then the single lines are read (asynchronously) and for every line your seperate callback function (lineReader.on('line', func);) would be called asynchronously but all that has happened so far, is that the event was registered. Then, (before your callback was even executed once), you log the graph.

All you need to do is add an eventlistener for the end of your reader which should look something like so:

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

Note that I haven't used these functions myself but this is what your problem looks like to me. Let me know if this works!

LBBO
  • 85
  • 1
  • 9