node.js - javascript reading data results in an empty object -
i have 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 graph in adjacency lists such as
1 3 2 3 2 1 3 3 1 2 1 i ran code node script.js. don't understand why @ end graph still empty object. what's correct way read data object?
try replacing console.log(graph); call with:
linereader.on('close', function () { console.log(graph); }); you see empty object because log happens before file read, reading async.
Comments
Post a Comment