Operation failed because worker thread is not running
Production Risk
Low — track worker state; implement restart logic for long-running worker pools.
Thrown when an operation is attempted on a Worker instance that is no longer running. Once a worker has exited (either normally or due to an error), operations such as postMessage() are no longer valid.
- 1Calling worker.postMessage() after the worker has exited
- 2Sending a message to a worker that crashed and emitted the error event
- 3Not tracking worker exit state before sending messages
Triggered when postMessage() or other operations are attempted on an already-terminated Worker.
const { Worker } = require('worker_threads');
const w = new Worker('./worker.js');
w.on('exit', () => {
w.postMessage('hello'); // throws — worker is no longer running
});expected output
Error [ERR_WORKER_NOT_RUNNING]: Worker is not running
Fix
Track worker running state and guard before posting messages
WHEN When workers may exit during operation
const { Worker } = require('worker_threads');
let running = true;
const w = new Worker('./worker.js');
w.on('exit', () => { running = false; });
function sendToWorker(msg) {
if (running) w.postMessage(msg);
}Why this works
A boolean flag updated on the exit event prevents postMessage from being called after termination.
const { Worker } = require('worker_threads');
const w = new Worker('./worker.js');
w.on('exit', () => {
w.postMessage('hello'); // throws — worker is no longer running
}); // this triggers ERR_WORKER_NOT_RUNNINGtry {
// operation that may throw ERR_WORKER_NOT_RUNNING
riskyOperation()
} catch (err) {
if (err.code === 'ERR_WORKER_NOT_RUNNING') {
console.error('ERR_WORKER_NOT_RUNNING:', err.message)
} else {
throw err
}
}let running = true
worker.on('exit', () => { running = false })
function send(msg) { if (running) worker.postMessage(msg) }✕ Post messages to workers in exit handlers
The worker is already terminated at exit time; messages cannot be delivered.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev