-1

I have created a script (block 1) and it fails to import anythign into my array. if i take the code and execute it line by line (block 2) in command line node it 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 the correct name, but the console.log(content.length) prints "0", where as in the node REPL content has upwards of 1700 entries.

I am using node v6.9.4 in a linux environment, and executing both blocks on the same computer. am I missing something obvious here?

thanks

azyth
  • 698
  • 5
  • 19
  • 1
    Because you type stuff into the console you inadvertently give enough time for the async operation to complete, not so when executing lines of code in a file. – James Jul 28 '17 at 17:42

1 Answers1

1

You can get the expected output when you 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 you enter in the node shell, your file is input stream completes in the interval that you take to type in the next line, and hence the content.length is available. However when executed in browser memory, engine reaches the line before the input has completed being read by the interface.

jagzviruz
  • 1,453
  • 12
  • 27