5

I need to be able to read a simple text file that contains a series of numbers for each line.

These numbers need to be read and stored somewhere in my code so I figure an array is the best way to go. Once the array has the values stored I can use it for further manipulation but I can't seem to actually read and push values into my array from each line in a text file.

What's the best way to do this? All help is appreciated! Thanks!

rodrigobdz
  • 47
  • 3
  • 13
Ashraff Hatz
  • 61
  • 1
  • 1
  • 3

2 Answers2

13
var fs = require('fs');
var readline = require('readline');
var stream = require('stream');

var instream = fs.createReadStream('./test.txt');
var outstream = new stream;
var rl = readline.createInterface(instream, outstream);

var arr = [];

rl.on('line', function(line) {
  // process line here
  arr.push(line);
});

rl.on('close', function() {
  // do something on finish here
  console.log('arr', arr);
});

This approach also handles large text file. https://coderwall.com/p/ohjerg/read-large-text-files-in-nodejs

kmsheng
  • 163
  • 6
  • Is there anyway to return the array instead of logging it ot the console (in the case where the above code was inside of a function)? – Dianne Mar 08 '22 at 21:22
2

Check out this answer.

This is the solution proposed there:

var lineReader = require('readline').createInterface({
  input: require('fs').createReadStream('file.in')
});

lineReader.on('line', function (line) {
  console.log('Line from file:', line);
});

Has also been added to the Node docs.

b-m-f
  • 1,278
  • 2
  • 13
  • 29