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

This question already has an answer here:

  • Read a file one line at a time in node.js? 25 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


    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

    上一篇: node.js:将文本文件读入数组。 (每一行都是数组中的一个项目。)

    下一篇: 如何逐行读取文件到node.js中的数组中