我需要在 JavaScript 中逐行读取文本文件。
可能需要对每一行执行某些操作(例如跳过或修改行),并将该行写入另一个文件。但是具体的操作不在此问题的范围内。
有许多类似措辞的问题,但大多数实际上是一次性将整个文件读入内存而不是逐行读取。因此,对于更大的文件,这些解决方案是无法使用的。
我需要在 JavaScript 中逐行读取文本文件。
可能需要对每一行执行某些操作(例如跳过或修改行),并将该行写入另一个文件。但是具体的操作不在此问题的范围内。
有许多类似措辞的问题,但大多数实际上是一次性将整个文件读入内存而不是逐行读取。因此,对于更大的文件,这些解决方案是无法使用的。
在Node.js的v18.11.0版本中,新增了一种按行读取文件的函数。
以下是使用该方法读取文本文件的示例:
import { open } from 'node:fs/promises';
myFileReader();
async function myFileReader() {
const file = await open('./TextFileName.txt');
for await (const line of file.readLines()) {
console.log(line)
}
}
想要了解更多,请查阅 Node.js 文档,这里是文件系统 readline() 的链接: https://nodejs.org/api/fs.html#filehandlereadlinesoptions
逐行读取文本文件的代码确实非常复杂,很难发现。
此代码使用NodeJS的readline模块逐行读写文本文件。它可以处理大文件。
const fs = require("fs");
const readline = require("readline");
const input_path = "input.txt";
const output_path = "output.txt";
const inputStream = fs.createReadStream(input_path);
const outputStream = fs.createWriteStream(output_path, { encoding: "utf8" });
var lineReader = readline.createInterface({
input: inputStream,
terminal: false,
});
lineReader.on("line", function (line) {
outputStream.write(line + "\n");
});
fetch
,但如果你已经有一个File,你可以调用stream()
和getReader()
来代替。async function* makeTextFileLineIterator(fileURL) {
const utf8Decoder = new TextDecoder("utf-8");
let response = await fetch(fileURL);
let reader = response.body.getReader();
let { value: chunk, done: readerDone } = await reader.read();
chunk = chunk ? utf8Decoder.decode(chunk, { stream: true }) : "";
let re = /\r\n|\n|\r/gm;
let startIndex = 0;
for (;;) {
let result = re.exec(chunk);
if (!result) {
if (readerDone) {
break;
}
let remainder = chunk.substr(startIndex);
({ value: chunk, done: readerDone } = await reader.read());
chunk =
remainder + (chunk ? utf8Decoder.decode(chunk, { stream: true }) : "");
startIndex = re.lastIndex = 0;
continue;
}
yield chunk.substring(startIndex, result.index);
startIndex = re.lastIndex;
}
if (startIndex < chunk.length) {
// last line didn't end in a newline char
yield chunk.substr(startIndex);
}
}
for await (let line of makeTextFileLineIterator(urlOfFile)) {
processLine(line);
}