Tiny Worker for Node.js

2.3.0 · active · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import { Worker } from 'tiny-worker';

// The worker's code is defined as a function. This function will be serialized and run in a separate Node.js child process.
const workerFunction = function () {
  // In a worker thread, 'self' refers to the global scope, similar to Web Workers.
  self.onmessage = function (ev) {
    console.log(`Worker ${process.pid} received: ${ev.data}`);
    // Simulate some work, e.g., reversing a string
    const result = ev.data.split('').reverse().join('');
    postMessage(`Worker ${process.pid} processed: ${result}`);
  };
  self.onerror = function (err) {
    console.error(`Worker ${process.pid} error:`, err.message);
  };
  console.log(`Worker ${process.pid} started.`);
};

// Create a new worker instance using the function above.
const worker = new Worker(workerFunction);

// Attach a message handler to receive messages back from the worker.
worker.onmessage = function (ev) {
  console.log('Main thread received:', ev.data);
  worker.terminate(); // Terminate the worker once the task is complete.
};

// Attach an error handler for errors originating from the worker.
worker.onerror = function (err) {
  console.error('Main thread error:', err.message);
  worker.terminate();
};

// Post a message to the worker to start a task.
worker.postMessage("Hello from the main thread!");

// Add process listeners to ensure graceful shutdown of workers if the main process is terminated.
process.on('SIGINT', () => {
  console.log('Main process SIGINT received, terminating worker...');
  worker.terminate();
  process.exit(0);
});

process.on('SIGTERM', () => {
  console.log('Main process SIGTERM received, terminating worker...');
  worker.terminate();
  process.exit(0);
});

view raw JSON →