Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file line by line into an array in node.js [duplicate]

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!

like image 403
Ashraff Hatz Avatar asked Dec 07 '22 17:12

Ashraff Hatz


1 Answers

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

like image 56
kmsheng Avatar answered Dec 10 '22 07:12

kmsheng