From 1fb53598e67a4f0e5cc2fa253cf7bccfb56a2405 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Mon, 22 Feb 2021 16:22:17 -0800 Subject: [PATCH] worker: add support for platformData The `worker.platformData` and `worker.setPlatformData()` APIs allow an arbitrary, cloneable JavaScript value to be set and passed to all new Worker instances spawned from the current context. It is similar to `workerData` except that `platformData` is set independently of the `new Worker()` constructor, and the the value is passed automatically to all new Workers. This is a *partial* fix of https://github.com/nodejs/node/issues/30992 but does not implement a complete fix. Signed-off-by: James M Snell --- doc/api/worker_threads.md | 40 ++++++++++++++++++++++ lib/internal/main/worker_thread.js | 2 ++ lib/internal/worker.js | 7 ++++ lib/worker_threads.js | 3 ++ test/parallel/test-worker-platform-data.js | 19 ++++++++++ 5 files changed, 71 insertions(+) create mode 100644 test/parallel/test-worker-platform-data.js diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index 7942788df58e5d..5af287916d0456 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -176,6 +176,32 @@ if (isMainThread) { } ``` +## `worker.platformData` + + +An arbitrary JavaScript value that contains a clone of the data passed +to the spawning threads `worker.setPlatformData()` function. The +`worker.platformData` is similar to `worker.workerData` except that +every new `Worker` receives it's own copy of `platformData` automatically. + +```js +const { + Worker, + isMainThread, + setPlatformData, + platformData +} = require('worker_threads'); + +if (isMainThread) { + setPlatformData('Hello World!'); + const worker = new Worker(__filename); +} else { + console.log(platformData); // Prints 'Hello, world!'. +} +``` + ## `worker.receiveMessageOnPort(port)` + +* `value` {any} Any arbitrary, cloneable JavaScript value that will be cloned + and passed automatically to all new `Worker` instances. + +The `worker.setPlatformData()` API sets the value of the `worker.platformData` +in all new `Worker` instances spawned from the current context. + +Calling `worker.setPlatformData()` will have no impact on the value of +`worker.platformData` on existing threads. + ## `worker.threadId`