AI写作智能体 自主规划任务,支持联网查询和网页读取,多模态高效创作各类分析报告、商业计划、营销方案、教学内容等。 广告
[TOC] > [参考](https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch#%E4%B8%8A%E4%BC%A0_json_%E6%95%B0%E6%8D%AE) ## 逐行处理文本文件 ``` 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 re = /\n|\r|\r\n/gm; let startIndex = 0; let result; 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) : ''); 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); } } async function run() { for await (let line of makeTextFileLineIterator(urlOfFile)) { processLine(line); } } run(); ```