Nodejs 終於有內建的 file.readLines()
在處理大型文字檔案(例如解析日誌檔案)時,出於效率和效能原因,推薦逐行載入/迭代內容,而不是將所有內容讀入記憶體。在 Nodejs 中,這一直很麻煩,因為從日常用戶的角度來看,逐行閱讀的方式看起來很繁瑣且太底層。不過,得益於最近合併到版本 v18.11.0
的PR,情況不再如此,現在有了內建的 FileHandle.prototype.readLines
,使用起來非常方便。
過去麻煩的方法
import fs from 'node:fs';
import readline from 'node:readline';
const fileStream = fs.createReadStream('input.txt');
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
for await (const line of rl) {
console.log(`Line from file: ${line}`);
}
現在方便的方式
import { open } from 'node:fs/promises';
const file = await open('input.txt');
for await (const line of file.readLines()) {
console.log(`Line from file: ${line}`);
}
PS:關於此方法是否應該從PR 增加到核心 nodejs 庫,存在一些爭論和討論。從最終用戶的角度來看,我認為這是一個很好的添加,它讓使用 nodejs 更方便地處理大型文字文件,並減少了記住readline
模組的方式所需的腦力負擔,並將程式碼行數減少了 50%,即使它只是readline
之上的一個包裝方法。
參考文獻