From 2fc759b9b847f5a4beebe7a0ac1616530a919c50 Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Fri, 1 Feb 2019 06:27:04 -0800 Subject: [PATCH] worker: no throw on property access/postMessage after termination PR-URL: https://github.com/nodejs/node/pull/25871 Reviewed-By: Anna Henningsen Reviewed-By: Gus Caplan Reviewed-By: Luigi Pinca Reviewed-By: Benjamin Gruenbaum Reviewed-By: Colin Ihrig Reviewed-By: Yuta Hiroto Reviewed-By: James M Snell --- lib/internal/worker.js | 8 +++++ test/parallel/test-worker-safe-getters.js | 38 +++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 test/parallel/test-worker-safe-getters.js diff --git a/lib/internal/worker.js b/lib/internal/worker.js index 1d1a5e7d228..6d833bcbd27 100644 --- a/lib/internal/worker.js +++ b/lib/internal/worker.js @@ -184,6 +184,8 @@ class Worker extends EventEmitter { } postMessage(...args) { + if (this[kPublicPort] === null) return; + this[kPublicPort].postMessage(...args); } @@ -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; } } diff --git a/test/parallel/test-worker-safe-getters.js b/test/parallel/test-worker-safe-getters.js new file mode 100644 index 00000000000..23c8de7c7b0 --- /dev/null +++ b/test/parallel/test-worker-safe-getters.js @@ -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); +}