worker_threads.markAsUntransferable(object)
object<any> 任意的 JavaScript 值。
将对象标记为不可转移。如果 object 出现在 port.postMessage() 调用的传输列表中,会抛出错误。如果 object 是原始值,则此操作无效。
🌐 Mark an object as not transferable. If object occurs in the transfer list of
a port.postMessage() call, an error is thrown. This is a no-op if
object is a primitive value.
特别是,这对于可以被克隆而不是转移的对象,以及在发送端被其他对象使用的对象是合理的。例如,Node.js 使用此方法标记它用于其 Buffer 泳池 的 ArrayBuffer。
在这样的数组缓冲区实例上,ArrayBuffer.prototype.transfer() 是不允许的。
🌐 In particular, this makes sense for objects that can be cloned, rather than
transferred, and which are used by other objects on the sending side.
For example, Node.js marks the ArrayBuffers it uses for its
Buffer pool with this.
ArrayBuffer.prototype.transfer() is disallowed on such array buffer
instances.
此操作无法撤消。
🌐 This operation cannot be undone.
import { MessageChannel, markAsUntransferable } from 'node:worker_threads';
const pooledBuffer = new ArrayBuffer(8);
const typedArray1 = new Uint8Array(pooledBuffer);
const typedArray2 = new Float64Array(pooledBuffer);
markAsUntransferable(pooledBuffer);
const { port1 } = new MessageChannel();
try {
// This will throw an error, because pooledBuffer is not transferable.
port1.postMessage(typedArray1, [ typedArray1.buffer ]);
} catch (error) {
// error.name === 'DataCloneError'
}
// The following line prints the contents of typedArray1 -- it still owns
// its memory and has not been transferred. Without
// `markAsUntransferable()`, this would print an empty Uint8Array and the
// postMessage call would have succeeded.
// typedArray2 is intact as well.
console.log(typedArray1);
console.log(typedArray2);'use strict';
const { MessageChannel, markAsUntransferable } = require('node:worker_threads');
const pooledBuffer = new ArrayBuffer(8);
const typedArray1 = new Uint8Array(pooledBuffer);
const typedArray2 = new Float64Array(pooledBuffer);
markAsUntransferable(pooledBuffer);
const { port1 } = new MessageChannel();
try {
// This will throw an error, because pooledBuffer is not transferable.
port1.postMessage(typedArray1, [ typedArray1.buffer ]);
} catch (error) {
// error.name === 'DataCloneError'
}
// The following line prints the contents of typedArray1 -- it still owns
// its memory and has not been transferred. Without
// `markAsUntransferable()`, this would print an empty Uint8Array and the
// postMessage call would have succeeded.
// typedArray2 is intact as well.
console.log(typedArray1);
console.log(typedArray2);浏览器中没有与此 API 等效的 API。
🌐 There is no equivalent to this API in browsers.