進捗を確認できるfetch
test
code:sh
code:script.js
let result = '';
const {size, iterator} = await fetchWithProgress(https://scrapbox.io/api/pages/takker);
for await (const buffer of iterator()) {
console.log([Reading]Size = ${buffer.byteLength} / ${size});
result += new TextDecoder().decode(buffer);
}
console.log(result);
async function fetchWithProgress(url, options) {
const res = await fetch(url, options);
const reader = res.body.getReader();
code:script.js
const contentEncoding = res.headers.get('content-encoding');
const contentLength = res.headers.get(contentEncoding ? 'x-file-size' : 'content-length');
code:script.js
return {
size: parseInt(contentLength),
iterator: async function*() {
while (true) {
const {value, done} = await reader.read();
if (done) break;
yield value; // 新しい通信が来る度に返す
}
},
};
}