An unsupported operation was performed on a worker thread.
Production Risk
Medium. This is a logic error that points to a misunderstanding of the worker thread model. It will cause the worker to terminate, which may affect application performance or correctness.
This error is thrown when you attempt to perform an action in a worker thread that is not supported. Worker threads have a different, more isolated execution context than the main thread. Certain operations, especially those that modify process-wide state like changing the current working directory (`process.chdir()`), are disallowed.
- 1Calling `process.chdir()` from within a worker thread.
- 2Attempting to set process-wide environment variables from a worker.
- 3Using other APIs that are explicitly documented as not being worker-thread-safe.
This error occurs when code running inside a `Worker` instance calls a Node.js API that has been explicitly disabled for non-main threads.
const { Worker, isMainThread } = require('worker_threads');
if (isMainThread) {
new Worker(__filename);
} else {
try {
process.chdir('../'); // This is not allowed in a worker.
} catch (err) {
console.error(err.code);
}
}expected output
ERR_WORKER_UNSUPPORTED_OPERATION
Fix
Perform Operation on Main Thread
WHEN An operation needs to affect the entire process.
const { Worker, isMainThread, parentPort } = require('worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
worker.on('message', (msg) => {
if (msg.command === 'chdir') {
process.chdir(msg.dir);
}
});
} else {
parentPort.postMessage({ command: 'chdir', dir: '../' });
}Why this works
Refactor your code so that process-wide operations are only performed on the main thread. Use `parentPort.postMessage()` to send a message from the worker to the main thread, requesting it to perform the operation.
const { Worker, isMainThread } = require('worker_threads');
if (isMainThread) {
new Worker(__filename);
} else {
try { // this triggers ERR_WORKER_UNSUPPORTED_OPERATIONtry {
// operation that may throw ERR_WORKER_UNSUPPORTED_OPERATION
riskyOperation()
} catch (err) {
if (err.code === 'ERR_WORKER_UNSUPPORTED_OPERATION') {
console.error('ERR_WORKER_UNSUPPORTED_OPERATION:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_worker_unsupported_operation(...args) {
// validate args here
return performOperation(...args)
}✕
https://github.com/nodejs/node/blob/main/lib/internal/worker.js
More information ↗Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev