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

这个问题在这里已经有了答案:

  • 在node.js中一次读取一行文件? 25个答案

  • 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);
    });
    

    这种方法也处理大文本文件。 https://coderwall.com/p/ohjerg/read-large-text-files-in-nodejs


    看看这个答案。

    这是在那里提出的解决方案:

    var lineReader = require('readline').createInterface({
      input: require('fs').createReadStream('file.in')
    });
    
    lineReader.on('line', function (line) {
      console.log('Line from file:', line);
    });
    

    也已添加到节点文档。

    链接地址: http://www.djcxy.com/p/52273.html

    上一篇: How to read a file line by line into an array in node.js

    下一篇: Read a file one line at a time in node.js?