js: TransformStream 浏览器上的流转换
class UpperCaseTransformStream {
constructor() {
return new TransformStream({
transform(chunk, controller) {
controller.enqueue(chunk.toUpperCase());
},
});
}
}
(async () => {
const response = await fetch("/index.js");
const readableStream = response.body
.pipeThrough(new TextDecoderStream()) // 将 uint8 转换为 text
.pipeThrough(new UpperCaseTransformStream());
const reader = readableStream.getReader();
let out = "";
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
out += value;
}
console.assert(out === 'CONSOLE.LOG(THIS);');
})();
See also: