node.js - Javascript script file code behaves differently then command in node -
this question has answer here:
- how return response asynchronous call? 21 answers
i have created script (block 1) , fails import anythign array. if take code , execute line line (block 2) in command line node works fine
block 1:
var fs = require('fs'); var readline = require('readline'); var filename = process.argv[2];//filename var content = []; console.log(filename); readline.createinterface({ input: fs.createreadstream(filename), terminal: false }).on('line', function (line) { content.push(line); }); console.log(content.length); block 2: (each line entered sequentially)
fs = require('fs'); readline = require('readline'); filename = "filename.txt"; content = []; readline.createinterface({ input: fs.createreadstream(filename), terminal: false }).on('line', function (line) { content.push(line); }); content; the console.log(filename) in block 1 prints out correct name, console.log(content.length) prints "0", in node repl content has upwards of 1700 entries.
i using node v6.9.4 in linux environment, , executing both blocks on same computer. missing obvious here?
thanks
you can expected output when use close event
readline.createinterface({ input: fs.createreadstream(filename), terminal: false }).on('line', function (line) { content.push(line); }).on('close', function(){ console.log(content.length); }) when enter in node shell, file input stream completes in interval take type in next line, , hence content.length available. when executed in browser memory, engine reaches line before input has completed being read interface.
Comments
Post a Comment