How to read a file line by line into an array in node.js
This question already has an answer here:
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
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.
链接地址: http://www.djcxy.com/p/52274.html