Node Worker Pool

3.0.2 · maintenance · verified Sun Apr 19

node-worker-pool is a JavaScript library for Node.js that provides a robust mechanism for managing a pool of child worker processes. It's designed for scenarios involving numerous highly parallelizable tasks, utilizing an exclusive message-passing paradigm rather than shared memory for inter-process communication. The library, currently at version 3.0.2, allows developers to define custom worker executables (though helper libraries are currently Node.js-specific) that communicate over `stdin`/`stdout` using a defined protocol. While its release cadence isn't explicitly documented, it focuses on stability and efficient task distribution. Key differentiators include its explicit message-passing design and the ability to use external executables as workers, offering flexibility beyond typical Node.js `worker_threads` when process isolation and custom language workers are desired.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a `WorkerPool` with a dynamically created worker script, send messages to the pool, and process responses, showing inter-process communication.

const fs = require('fs');
const path = require('path');
const WorkerPool = require('node-worker-pool');

const workerScriptContent = `
var workerUtils = require('node-worker-pool/nodeWorkerUtils');

var initData;
function onInitialize(data) {
  initData = data;
}

function onMessage(data) {
  return {
    initData: initData,
    receivedData: data,
    pid: process.pid
  };
}

if (require.main === module) {
  try {
    workerUtils.startWorker(onInitialize, onMessage);
  } catch (e) {
    workerUtils.respondWithError(e);
  }
}
`;

// Create a temporary worker file
const workerFilePath = path.join(__dirname, 'temp-worker.js');
fs.writeFileSync(workerFilePath, workerScriptContent);

async function runPool() {
  console.log('Starting worker pool...');
  const workerPool = new WorkerPool(
    2, // Use 2 workers for demonstration
    process.execPath, // Path to the node binary
    workerFilePath,   // Path to the temporary worker script
    {
      initData: { someUsefulConstant: 42 }
    }
  );

  try {
    console.log('Sending messages to workers...');
    const responses = await Promise.all([
      workerPool.sendMessage({ message: 'Hello from main 1!' }),
      workerPool.sendMessage({ message: 'Hello from main 2!' }),
      workerPool.sendMessage({ message: 'Hello from main 3!' })
    ]);

    responses.forEach((response, index) => {
      console.log(`Response ${index + 1}:`, response);
    });

    console.log('Shutting down worker pool...');
    await workerPool.shutDown();
    console.log('All worker processes have now been killed.');
  } catch (error) {
    console.error('An error occurred:', error);
  } finally {
    // Clean up the temporary worker file
    fs.unlinkSync(workerFilePath);
    process.exit(0);
  }
}

runPool();

view raw JSON →