From 3c6f12c965f7188d81c1a74df88aeec7aa19073e Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Sun, 10 Sep 2017 01:43:55 +0200 Subject: [PATCH] worker: implement worker.moveMessagePortToContext() This enables using `MessagePort`s in different `vm.Context`s, aiding with the isolation that the `vm` module seeks to provide. Refs: https://github.com/ayojs/ayo/pull/111 PR-URL: https://github.com/nodejs/node/pull/26497 Reviewed-By: James M Snell --- doc/api/worker_threads.md | 27 ++++++++ lib/internal/worker/io.js | 2 + lib/worker_threads.js | 4 +- src/node_messaging.cc | 39 ++++++++++- src/node_messaging.h | 5 ++ .../parallel/test-worker-message-port-move.js | 69 +++++++++++++++++++ 6 files changed, 142 insertions(+), 4 deletions(-) create mode 100644 test/parallel/test-worker-message-port-move.js diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index 70800fbe3778e6..08b2e3c5d50166 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -70,6 +70,30 @@ if (isMainThread) { } ``` +## worker.moveMessagePortToContext(port, contextifiedSandbox) + + +* `port` {MessagePort} The message port which will be transferred. +* `contextifiedSandbox` {Object} A [contextified][] object as returned by the + `vm.createContext()` method. + +* Returns: {MessagePort} + +Transfer a `MessagePort` to a different [`vm`][] Context. The original `port` +object will be rendered unusable, and the returned `MessagePort` instance will +take its place. + +The returned `MessagePort` will be an object in the target context, and will +inherit from its global `Object` class. Objects passed to the +[`port.onmessage()`][] listener will also be created in the target context +and inherit from its global `Object` class. + +However, the created `MessagePort` will no longer inherit from +[`EventEmitter`][], and only [`port.onmessage()`][] can be used to receive +events using it. + ## worker.parentPort