diff --git a/README.md b/README.md index 80d1b3f..8fd244d 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,8 @@ This module works with `yarn` in PnP (plug'n play) mode too! ### Emit events You can emit events on the ThreadStream from your worker using [`worker.parentPort.postMessage()`](https://nodejs.org/api/worker_threads.html#workerparentport). -The message (JSON object) must have the following data structure: +Messages that do not carry a thread-stream protocol `code` are ignored. +For custom events, the message (JSON object) must have the following data structure: ```js parentPort.postMessage({ diff --git a/index.js b/index.js index db2b23b..d30d11c 100644 --- a/index.js +++ b/index.js @@ -174,6 +174,12 @@ function onWorkerMessage (msg) { return } + // Node.js watch mode may send internal worker messages that do not + // participate in thread-stream's worker protocol. + if (msg?.code == null) { + return + } + switch (msg.code) { case 'READY': // Replace the FakeWeakRef with a diff --git a/test/message-without-code.js b/test/message-without-code.js new file mode 100644 index 0000000..d06db9d --- /dev/null +++ b/test/message-without-code.js @@ -0,0 +1,19 @@ +'use strict' + +const { Writable } = require('stream') +const { parentPort } = require('worker_threads') + +async function run () { + parentPort.postMessage({ + internal: 'watch-mode' + }) + + return new Writable({ + autoDestroy: true, + write (chunk, enc, cb) { + cb() + } + }) +} + +module.exports = run diff --git a/test/watch-mode.test.js b/test/watch-mode.test.js new file mode 100644 index 0000000..9c06fb4 --- /dev/null +++ b/test/watch-mode.test.js @@ -0,0 +1,28 @@ +'use strict' + +const { test } = require('tap') +const { join } = require('path') +const ThreadStream = require('..') + +test('ignores worker messages without a protocol code', function (t) { + t.plan(2) + + const stream = new ThreadStream({ + filename: join(__dirname, 'message-without-code.js'), + sync: false + }) + + const errors = [] + stream.on('error', err => { + errors.push(err) + }) + + stream.on('ready', () => { + t.ok(stream.write('hello world\n')) + stream.end() + }) + + stream.on('finish', () => { + t.same(errors, []) + }) +})