首頁  >  文章  >  後端開發  >  在node.js中一次讀取一行檔案?

在node.js中一次讀取一行檔案?

王林
王林轉載
2024-02-05 23:00:04634瀏覽

在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 之類的東西,但我想弄清楚這一點。

我認為另一個答案不起作用,因為該檔案比我運行它的伺服器的記憶體大得多。


正確答案


自 Node.js v0.12 和 Node.js v4.0.0 起,有一個穩定的 readline核心模組。這是從檔案中讀取行的最簡單方法,無需任何外部模組:

<code>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();
</code>

或:

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

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

lineReader.on('close', function () {
    console.log('all done, son');
});

即使沒有最終的 \n,最後一行也能正確讀取(從 Node v0.12 或更高版本開始)。

更新:此範例已新增至 Node 的 API 官方文件.

以上是在node.js中一次讀取一行檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除