Skip to content

Commit 5d2e064

Browse files
chjjtargos
authored andcommitted
worker: no throw on property access/postMessage after termination
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]>
1 parent 8c9800c commit 5d2e064

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

lib/internal/worker.js

+8
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,8 @@ class Worker extends EventEmitter {
184184
}
185185

186186
postMessage(...args) {
187+
if (this[kPublicPort] === null) return;
188+
187189
this[kPublicPort].postMessage(...args);
188190
}
189191

@@ -219,14 +221,20 @@ class Worker extends EventEmitter {
219221
}
220222

221223
get stdin() {
224+
if (this[kParentSideStdio] === null) return null;
225+
222226
return this[kParentSideStdio].stdin;
223227
}
224228

225229
get stdout() {
230+
if (this[kParentSideStdio] === null) return null;
231+
226232
return this[kParentSideStdio].stdout;
227233
}
228234

229235
get stderr() {
236+
if (this[kParentSideStdio] === null) return null;
237+
230238
return this[kParentSideStdio].stderr;
231239
}
232240
}
+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
'use strict';
2+
3+
const common = require('../common');
4+
5+
const assert = require('assert');
6+
const { Worker, isMainThread } = require('worker_threads');
7+
8+
if (isMainThread) {
9+
const w = new Worker(__filename, {
10+
stdin: true,
11+
stdout: true,
12+
stderr: true
13+
});
14+
15+
w.on('exit', common.mustCall((code) => {
16+
assert.strictEqual(code, 0);
17+
18+
// `postMessage` should not throw after termination
19+
// (this mimics the browser behavior).
20+
w.postMessage('foobar');
21+
w.ref();
22+
w.unref();
23+
24+
// Although not browser specific, probably wise to
25+
// make sure the stream getters don't throw either.
26+
w.stdin;
27+
w.stdout;
28+
w.stderr;
29+
30+
// Sanity check.
31+
assert.strictEqual(w.threadId, -1);
32+
assert.strictEqual(w.stdin, null);
33+
assert.strictEqual(w.stdout, null);
34+
assert.strictEqual(w.stderr, null);
35+
}));
36+
} else {
37+
process.exit(0);
38+
}

0 commit comments

Comments
 (0)