Blob 对象和 MessageChannel
¥Blob
objects and MessageChannel
一旦创建了 <Blob> 对象,就可以通过 MessagePort
将其发送到多个目标,而无需传输或立即复制数据。只有在调用 arrayBuffer()
或 text()
方法时,才会复制 Blob
包含的数据。
¥Once a <Blob> object is created, it can be sent via MessagePort
to multiple
destinations without transferring or immediately copying the data. The data
contained by the Blob
is copied only when the arrayBuffer()
or text()
methods are called.
import { Blob } from 'node:buffer';
import { setTimeout as delay } from 'node:timers/promises';
const blob = new Blob(['hello there']);
const mc1 = new MessageChannel();
const mc2 = new MessageChannel();
mc1.port1.onmessage = async ({ data }) => {
console.log(await data.arrayBuffer());
mc1.port1.close();
};
mc2.port1.onmessage = async ({ data }) => {
await delay(1000);
console.log(await data.arrayBuffer());
mc2.port1.close();
};
mc1.port2.postMessage(blob);
mc2.port2.postMessage(blob);
// The Blob is still usable after posting.
blob.text().then(console.log);
const { Blob } = require('node:buffer');
const { setTimeout: delay } = require('node:timers/promises');
const blob = new Blob(['hello there']);
const mc1 = new MessageChannel();
const mc2 = new MessageChannel();
mc1.port1.onmessage = async ({ data }) => {
console.log(await data.arrayBuffer());
mc1.port1.close();
};
mc2.port1.onmessage = async ({ data }) => {
await delay(1000);
console.log(await data.arrayBuffer());
mc2.port1.close();
};
mc1.port2.postMessage(blob);
mc2.port2.postMessage(blob);
// The Blob is still usable after posting.
blob.text().then(console.log);