企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[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(); ```