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!

2

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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)?
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.