From c182198c44e71bd0e62af84c79f9a116807cea72 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Wed, 12 May 2021 15:10:32 -0700 Subject: [PATCH] process: add `'worker'` event MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Provides a new `process.on('worker', (worker) => {})` event that is triggered by the creation of a new `worker_thread.Worker`. The use case is to allow hooks to be installed for monitoring workers without having to modify the call sites around those. Signed-off-by: James M Snell PR-URL: https://github.com/nodejs/node/pull/38659 Reviewed-By: Anna Henningsen Reviewed-By: Rich Trott Reviewed-By: Gerhard Stöbich --- doc/api/process.md | 9 +++++++++ lib/internal/worker.js | 2 ++ test/parallel/test-worker-event.js | 13 +++++++++++++ 3 files changed, 24 insertions(+) create mode 100644 test/parallel/test-worker-event.js diff --git a/doc/api/process.md b/doc/api/process.md index 95dd6a87855954..0e852dcb100acc 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -457,6 +457,15 @@ of the custom deprecation. The `*-deprecation` command-line flags only affect warnings that use the name `'DeprecationWarning'`. +### Event: `'worker'` + + +* `worker` {Worker} The {Worker} that was created. + +The `'worker'` event is emitted after a new {Worker} thread has been created. + #### Emitting custom warnings See the [`process.emitWarning()`][process_emit_warning] method for issuing diff --git a/lib/internal/worker.js b/lib/internal/worker.js index f1da0d4ded4cea..f2414ebeec4aae 100644 --- a/lib/internal/worker.js +++ b/lib/internal/worker.js @@ -266,6 +266,8 @@ class Worker extends EventEmitter { }; // Actually start the new thread now that everything is in place. this[kHandle].startThread(); + + process.nextTick(() => process.emit('worker', this)); } [kOnExit](code, customErr, customErrReason) { diff --git a/test/parallel/test-worker-event.js b/test/parallel/test-worker-event.js new file mode 100644 index 00000000000000..9d6056e1091468 --- /dev/null +++ b/test/parallel/test-worker-event.js @@ -0,0 +1,13 @@ +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const { + Worker, +} = require('worker_threads'); + +process.on('worker', common.mustCall(({ threadId }) => { + assert.strictEqual(threadId, 1); +})); + +new Worker('', { eval: true });