此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
TransformStreamDefaultController
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2022年6月.
Stream API 的 TransformStreamDefaultController 接口提供了操作关联的 ReadableStream 和 WritableStream 的方法。
当构造 TransformStream 时,会创建一个 TransformStreamDefaultController。因此它没有构造函数。获取 TransformStreamDefaultController 实例的方式是通过 TransformStream() 的回调方法。
实例属性
TransformStreamDefaultController.desiredSize只读-
返回填充满流内部队列的可读端所需要的大小。
实例方法
TransformStreamDefaultController.enqueue()-
排入一个分块(单个数据)到流的可读端。
TransformStreamDefaultController.error()-
转换流的可写端和可读端都出现错误。
TransformStreamDefaultController.terminate()-
关闭流的可读端并且流的可写端出错。
示例
在下面的示例中,一个转换流接收所有的分块将其转换为 Uint8Array,使用了 error() 和 enqueue() 方法。
js
const transformContent = {
start() {}, // required.
async transform(chunk, controller) {
chunk = await chunk;
switch (typeof chunk) {
case "object":
// just say the stream is done I guess
if (chunk === null) controller.terminate();
else if (ArrayBuffer.isView(chunk))
controller.enqueue(
new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength),
);
else if (
Array.isArray(chunk) &&
chunk.every((value) => typeof value === "number")
)
controller.enqueue(new Uint8Array(chunk));
else if (
"function" === typeof chunk.valueOf &&
chunk.valueOf() !== chunk
)
this.transform(chunk.valueOf(), controller); // hack
else if ("toJSON" in chunk)
this.transform(JSON.stringify(chunk), controller);
break;
case "symbol":
controller.error("Cannot send a symbol as a chunk part");
break;
case "undefined":
controller.error("Cannot send undefined as a chunk part");
break;
default:
controller.enqueue(this.textencoder.encode(String(chunk)));
break;
}
},
flush() {
/* do any destructor work here */
},
};
class AnyToU8Stream extends TransformStream {
constructor() {
super({ ...transformContent, textencoder: new TextEncoder() });
}
}
规范
| Specification |
|---|
| Streams> # ts-default-controller-class> |
浏览器兼容性
Loading...