js请求读取后端大文件时 如何分段读取
场景
:当前我们做这个周报生成器,请求的时候会很慢,如果js正常请求会导致等待时间过长,用户体验感就很差,如果能一边读取一边把请求响应数据加载出来该多好,代码如下。
async loadNovel() {
// const resp = await fetch(url);
let resp = await fetch("https://weekly-report.com", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body:JSON.stringify({
prompt: '请帮我编写100字的工作内容填充为一篇软件开发完整的周报,用 markdown 格式以分点叙述的形式输出:小程序测试'
}),
});
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let remainChunk = new Uint8Array(0);
for (;;) {
const { value, done } = await reader.read();
if (done) {
break;
}
const lastIndex = value.lastIndexOf(10);
const chunk = value.slice(0, lastIndex + 1);
const readChunk = new Uint8Array(remainChunk.length + chunk.length);
readChunk.set(remainChunk);
readChunk.set(chunk, remainChunk.length);
remainChunk = value.slice(lastIndex + 1);
const text = decoder.decode(readChunk);
console.log(text);
}
const text = decoder.decode(remainChunk);
console.log(text);
},
request(){
let t = this;
t.loadNovel();
},
原创文章,转载请注明:js请求读取后端大文件时 如何分段读取 | 知识改变命运
转载请注明出处: 知识改变命运 » js请求读取后端大文件时 如何分段读取