Skip to content

Commit

Permalink
worker: no throw on property access/postMessage after termination
Browse files Browse the repository at this point in the history
PR-URL: #25871
Reviewed-By: Anna Henningsen <[email protected]>
Reviewed-By: Gus Caplan <[email protected]>
Reviewed-By: Luigi Pinca <[email protected]>
Reviewed-By: Benjamin Gruenbaum <[email protected]>
Reviewed-By: Colin Ihrig <[email protected]>
Reviewed-By: Yuta Hiroto <[email protected]>
Reviewed-By: James M Snell <[email protected]>
  • Loading branch information
chjj authored and targos committed Feb 10, 2019
1 parent 8c9800c commit 5d2e064
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/internal/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,8 @@ class Worker extends EventEmitter {
}

postMessage(...args) {
if (this[kPublicPort] === null) return;

this[kPublicPort].postMessage(...args);
}

Expand Down Expand Up @@ -219,14 +221,20 @@ class Worker extends EventEmitter {
}

get stdin() {
if (this[kParentSideStdio] === null) return null;

return this[kParentSideStdio].stdin;
}

get stdout() {
if (this[kParentSideStdio] === null) return null;

return this[kParentSideStdio].stdout;
}

get stderr() {
if (this[kParentSideStdio] === null) return null;

return this[kParentSideStdio].stderr;
}
}
Expand Down
38 changes: 38 additions & 0 deletions test/parallel/test-worker-safe-getters.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
'use strict';

const common = require('../common');

const assert = require('assert');
const { Worker, isMainThread } = require('worker_threads');

if (isMainThread) {
const w = new Worker(__filename, {
stdin: true,
stdout: true,
stderr: true
});

w.on('exit', common.mustCall((code) => {
assert.strictEqual(code, 0);

// `postMessage` should not throw after termination
// (this mimics the browser behavior).
w.postMessage('foobar');
w.ref();
w.unref();

// Although not browser specific, probably wise to
// make sure the stream getters don't throw either.
w.stdin;
w.stdout;
w.stderr;

// Sanity check.
assert.strictEqual(w.threadId, -1);
assert.strictEqual(w.stdin, null);
assert.strictEqual(w.stdout, null);
assert.strictEqual(w.stderr, null);
}));
} else {
process.exit(0);
}

0 comments on commit 5d2e064

Please sign in to comment.