我有使用
ReadableStream
运行文本文件的代码,并在其中找到一些日志行。目前,这对我来说适用于 Node.js 后端的 fetch
API 和 FileHandle.readableWebStream
。
该代码基于 MDN 上的此代码:
async function* makeTextFileLineIterator(fileURL) {
const utf8Decoder = new TextDecoder("utf-8");
const response = await fetch(fileURL);
const reader = response.body.getReader();
let { value: chunk, done: readerDone } = await reader.read();
chunk = chunk ? utf8Decoder.decode(chunk) : "";
const newline = /\r?\n/gm;
let startIndex = 0;
let result;
while (true) {
const result = newline.exec(chunk);
if (!result) {
if (readerDone) break;
const remainder = chunk.substr(startIndex);
({ value: chunk, done: readerDone } = await reader.read());
chunk = remainder + (chunk ? utf8Decoder.decode(chunk) : "");
startIndex = newline.lastIndex = 0;
continue;
}
yield chunk.substring(startIndex, result.index);
startIndex = newline.lastIndex;
}
if (startIndex < chunk.length) {
// Last line didn't end in a newline char
yield chunk.substr(startIndex);
}
}
我做了一些修改,但这对于那些总是需要问题中包含一些代码的人来说应该足够了。
我还希望能够直接从 HTML
file
输入解析此日志文件。我想避免读取内存中的整个文件,因为这些文件最大可达 3 GB,而我所需要做的就是找到各个日志行。
如何将文件从文件输入转换为
ReadableStream
并逐块读取它们而不是一次全部读取?
事实证明这实际上非常简单,我只是找不到正确的搜索查询来找到它:
const fileInput = main.querySelector("input.fileread");
const file = fileInput.files[0];
const stream = file.stream();
// usefull for displaying progress
const expectedSize = file.size;
const reader = stream.getReader();