Skip to content

Commit

Permalink
process: add 'worker' event
Browse files Browse the repository at this point in the history
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 <jasnell@gmail.com>

PR-URL: #38659
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Gerhard Stöbich <deb2001-github@yahoo.de>
  • Loading branch information
jasnell committed May 14, 2021
1 parent aefc621 commit 2c80048
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
9 changes: 9 additions & 0 deletions doc/api/process.md
Expand Up @@ -457,6 +457,15 @@ of the custom deprecation.
The `*-deprecation` command-line flags only affect warnings that use the name
`'DeprecationWarning'`.

### Event: `'worker'`
<!-- YAML
added: REPLACEME
-->

* `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
Expand Down
2 changes: 2 additions & 0 deletions lib/internal/worker.js
Expand Up @@ -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) {
Expand Down
13 changes: 13 additions & 0 deletions 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 });

0 comments on commit 2c80048

Please sign in to comment.