小编典典

在node.js中一次读取一行文件?

node.js

我正在尝试一次读取一行大文件。我在Quora上发现了一个与该主题有关的问题,但我缺少一些联系以使整个组件组合在一起。

 var Lazy=require("lazy");
 new Lazy(process.stdin)
     .lines
     .forEach(
          function(line) { 
              console.log(line.toString()); 
          }
 );
 process.stdin.resume();

我想弄清楚的一点是,如何一次从文件而不是如本示例中的STDIN读取一行。

我试过了:

 fs.open('./VeryBigFile.csv', 'r', '0666', Process);

 function Process(err, fd) {
    if (err) throw err;
    // DO lazy read 
 }

但它不起作用。我知道,在紧急情况下,我可能会转而使用PHP之类的东西,但是我想弄清楚这一点。

我不认为其他答案会起作用,因为该文件比我在其上运行的具有内存的服务器大得多。


阅读 321

收藏
2020-07-07

共1个答案

小编典典

从Node.js v0.12和Node.js
v4.0.0开始,有一个稳定的readline核心模块。这是从文件中读取行的最简单方法,而无需任何外部模块:

const fs = require('fs');
const readline = require('readline');

async function processLineByLine() {
  const fileStream = fs.createReadStream('input.txt');

  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity
  });
  // Note: we use the crlfDelay option to recognize all instances of CR LF
  // ('\r\n') in input.txt as a single line break.

  for await (const line of rl) {
    // Each line in input.txt will be successively available here as `line`.
    console.log(`Line from file: ${line}`);
  }
}

processLineByLine();

或者:

var lineReader = require('readline').createInterface({
  input: require('fs').createReadStream('file.in')
});

lineReader.on('line', function (line) {
  console.log('Line from file:', line);
});

即使没有final,也可以正确读取最后一行(从Node v0.12或更高版本开始)\n

更新
:此示例已添加到Node的API官方文档中

2020-07-07