{"id":12145,"library":"tiny-worker","title":"Tiny Worker for Node.js","description":"tiny-worker is a lightweight JavaScript library that provides a Web Worker-like API for Node.js environments, allowing developers to offload CPU-intensive tasks to separate threads, similar to the browser's `Worker` interface. It leverages Node.js's `child_process.fork()` module internally, offering a familiar `onmessage`, `postMessage`, and `terminate` API. The current stable version is 2.3.0, with its release cadence historically driven by feature enhancements and bug resolutions rather than a fixed schedule. A key differentiator is its flexibility in module loading within worker scripts, supporting Node.js `require()` by default and offering an `esm: true` option to enable ES6 `import`/`export` syntax, catering to diverse project setups. It is specifically designed for server-side use cases to improve application responsiveness by preventing the main event loop from being blocked by computationally intensive operations.","status":"active","version":"2.3.0","language":"javascript","source_language":"en","source_url":"https://github.com/avoidwork/tiny-worker","tags":["javascript","web","worker","ps","webworker"],"install":[{"cmd":"npm install tiny-worker","lang":"bash","label":"npm"},{"cmd":"yarn add tiny-worker","lang":"bash","label":"yarn"},{"cmd":"pnpm add tiny-worker","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary `Worker` constructor is available as a named export for ESM. CommonJS `require()` is also supported and widely shown in README examples, which directly returns the `Worker` constructor.","wrong":"const Worker = require('tiny-worker');","symbol":"Worker","correct":"import { Worker } from 'tiny-worker';"},{"note":"`setRange` is a static method of the `Worker` class, used to configure the debug port range for child processes to avoid conflicts.","wrong":"import { setRange } from 'tiny-worker'; setRange(min, max);","symbol":"Worker.setRange","correct":"import { Worker } from 'tiny-worker'; Worker.setRange(min, max);"},{"note":"When instantiating a `Worker` with `{ esm: true }` in its options, worker scripts can use `import` statements for their dependencies. By default, `require()` is available within the worker script scope.","wrong":"const someHelper = require('./helper');","symbol":"Worker script (ESM)","correct":"import { someHelper } from './helper.js';"}],"quickstart":{"code":"import { Worker } from 'tiny-worker';\n\n// The worker's code is defined as a function. This function will be serialized and run in a separate Node.js child process.\nconst workerFunction = function () {\n  // In a worker thread, 'self' refers to the global scope, similar to Web Workers.\n  self.onmessage = function (ev) {\n    console.log(`Worker ${process.pid} received: ${ev.data}`);\n    // Simulate some work, e.g., reversing a string\n    const result = ev.data.split('').reverse().join('');\n    postMessage(`Worker ${process.pid} processed: ${result}`);\n  };\n  self.onerror = function (err) {\n    console.error(`Worker ${process.pid} error:`, err.message);\n  };\n  console.log(`Worker ${process.pid} started.`);\n};\n\n// Create a new worker instance using the function above.\nconst worker = new Worker(workerFunction);\n\n// Attach a message handler to receive messages back from the worker.\nworker.onmessage = function (ev) {\n  console.log('Main thread received:', ev.data);\n  worker.terminate(); // Terminate the worker once the task is complete.\n};\n\n// Attach an error handler for errors originating from the worker.\nworker.onerror = function (err) {\n  console.error('Main thread error:', err.message);\n  worker.terminate();\n};\n\n// Post a message to the worker to start a task.\nworker.postMessage(\"Hello from the main thread!\");\n\n// Add process listeners to ensure graceful shutdown of workers if the main process is terminated.\nprocess.on('SIGINT', () => {\n  console.log('Main process SIGINT received, terminating worker...');\n  worker.terminate();\n  process.exit(0);\n});\n\nprocess.on('SIGTERM', () => {\n  console.log('Main process SIGTERM received, terminating worker...');\n  worker.terminate();\n  process.exit(0);\n});\n","lang":"javascript","description":"This quickstart demonstrates how to create a worker from an inline function, send a message to it, receive a processed response, and ensure the worker is gracefully terminated upon completion or main process shutdown."},"warnings":[{"fix":"Implement `process.on('SIGTERM', ...)` and `process.on('SIGINT', ...)` listeners in your main script to call `worker.terminate()` for all active workers before `process.exit(0);`.","message":"Workers created by `tiny-worker` are Node.js child processes. If the main process exits without explicitly terminating workers, they can become orphaned. This is a common cause of lingering processes, consuming system resources.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Use `Worker.setRange(min, max)` in the main process to configure the automatic debug port range. For full manual control, pass `{ noDebugRedirection: true, execArgv: ['--inspect=PORT'] }` in the worker options, specifying a unique port.","message":"Debugging Node.js child processes requires separate debug ports. `tiny-worker` attempts automatic port redirection to avoid conflicts, but this can cause issues or require manual configuration if specific port ranges or debugging setups are needed.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"When creating a worker from a file, pass `{ esm: true }` in the worker options object: `new Worker('worker.js', [], { esm: true });`.","message":"The default module system for scripts executed within `tiny-worker` is CommonJS (`require()`). If you intend to use ES Modules (`import`/`export`) syntax in your worker files, you must explicitly enable it.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always refer to `self.onmessage` and `self.postMessage` within worker scripts. Be mindful of which global objects are available and their behavior compared to the main Node.js thread.","message":"Worker scripts run in an isolated scope, analogous to browser Web Workers. While Node.js global objects like `process` are available, `self` is the direct global context for worker-specific APIs like `onmessage` and `postMessage`, not `global` or `window`.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Add `process.on('SIGINT', () => { worker.terminate(); process.exit(0); });` (and `SIGTERM`) to your main application to ensure workers are shut down cleanly on process termination.","cause":"The main Node.js process terminated abruptly without explicitly terminating its `tiny-worker` child processes.","error":"An orphaned child process that lives on past the parent process' lifespan"},{"fix":"Rewrite the worker script to use ES Module `import`/`export` syntax, or remove the `{ esm: true }` option from the `Worker` constructor if CommonJS is intended.","cause":"You are attempting to use CommonJS `require()` syntax inside a worker script that was initialized with the `{ esm: true }` option, forcing an ES Module context.","error":"ReferenceError: require is not defined"},{"fix":"When creating the worker from a file, pass `{ esm: true }` in the worker options: `new Worker('worker.js', [], { esm: true });`.","cause":"You are attempting to use ES Module `import`/`export` syntax inside a worker script that was *not* initialized with the `{ esm: true }` option, causing it to run in a CommonJS context.","error":"SyntaxError: Cannot use import statement outside a module"},{"fix":"Configure debug port redirection using `Worker.setRange(min, max)` in the main process. Alternatively, explicitly set `execArgv` with `--inspect=PORT` and `noDebugRedirection: true` in worker options to assign a unique, non-conflicting port.","cause":"Debugging ports are conflicting between the parent and child processes, or the debugger is not correctly attaching to the child process due to port issues.","error":"Debugger listening on ws://127.0.0.1:xxxx/ws-id-xxxx... Waiting for the debugger to disconnect..."}],"ecosystem":"npm"}