Registry / devops / gatsby-worker

gatsby-worker

JSON →
library2.16.0jsnpmunverified

gatsby-worker is a utility package within the Gatsby ecosystem, currently at version `2.16.0`, designed for creating worker pools to offload CPU-intensive tasks into separate Node.js processes. Inspired by `jest-worker`, it enables efficient parallel execution, improving build times and overall performance for Gatsby sites. The package follows Gatsby's release cadence, typically aligning with major and minor Gatsby releases, which often see minor versions published every two weeks for the core framework. It provides a type-safe API, allowing developers to define worker modules with explicit function signatures using TypeScript. Key features include queuing tasks on single or all workers, robust parent-worker messaging capabilities, and granular control over worker lifecycle and environment variables. It requires Node.js versions `>=18.0.0 <26` for operation.

npm install gatsby-worker
INSTALL
IMPORT
SIG · GATSBY-WORKER
G
gatsby-worker
devopsjavascriptv2.16.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

WorkerPool
import { WorkerPool } from 'gatsby-worker'
const { WorkerPool } = require('gatsby-worker')
Prefer ES Module import syntax. While `require.resolve` is used for worker path configuration, the library's primary API is designed for ES Modules.
isWorker
import { isWorker } from 'gatsby-worker'
const isWorker = require('gatsby-worker').isWorker
Used to conditionally execute code based on whether it's running in the main process or a worker thread.
getMessenger
import { getMessenger } from 'gatsby-worker'
const getMessenger = require('gatsby-worker').getMessenger
Enables type-safe messaging between parent and child worker processes. Define shared message types for best practice.

This quickstart demonstrates how to create a worker pool, define CPU-intensive tasks in a separate worker file, execute tasks on single or all workers, and gracefully shut down the pool, while also showcasing environment variable passing and logging.

/* File: worker.ts */ // This file defines the tasks that will be executed in a worker thread. // It should be a separate file resolved by the WorkerPool. export async function heavyTask(param: string): Promise<string> { // Simulate a CPU-intensive operation let result = 0; for (let i = 0; i < 10_000_000; i++) { result += Math.sqrt(i); } return `Processed '${param}' with result: ${result.toFixed(2)}`; } export async function setupStep(param: string): Promise<void> { console.log(`Worker ${process.env.GATSBY_WORKER_ID || 'unknown'} setting up with: ${param}`); // Simulate a heavy setup process await new Promise(resolve => setTimeout(resolve, 100)); } /* File: parent.ts */ import { WorkerPool } from 'gatsby-worker'; import * as path from 'path'; // Assuming 'worker.ts' is compiled to 'worker.js' in the same directory for Node.js execution const workerPath = path.resolve(__dirname, 'worker.js'); async function runWorkers() { const workerPool = new WorkerPool<typeof import('./worker')>( workerPath, { numWorkers: 2, // Use 2 worker threads env: { CUSTOM_ENV_VAR_TO_SET_IN_WORKER: 'foo', }, silent: false, // Output from workers will be logged to parent's console } ); try { console.log('--- Queuing setup on all workers ---'); // Queue a task on all workers for initial setup await Promise.all(workerPool.all.setupStep('initial setup data')); console.log('All workers setup complete.'); console.log('\n--- Queuing heavy tasks ---'); // Queue a task on a single worker (gatsby-worker handles worker assignment) const singleTaskPromise1 = workerPool.single.heavyTask('data-chunk-A'); const singleTaskPromise2 = workerPool.single.heavyTask('data-chunk-B'); const singleTaskPromise3 = workerPool.single.heavyTask('data-chunk-C'); const results = await Promise.all([ singleTaskPromise1, singleTaskPromise2, singleTaskPromise3 ]); results.forEach(res => console.log(res)); } catch (error) { console.error('An error occurred:', error); } finally { console.log('\n--- Shutting down worker pool ---'); await workerPool.end(); // Shut down all workers console.log('Worker pool shut down.'); } } runWorkers();
Debug
Known issues
breakingGatsby and its associated packages, including `gatsby-worker`, adhere to strict Node.js version compatibility policies. Major Gatsby releases often drop support for older Node.js versions, aligning with Node.js LTS schedules. Ensure your development and deployment environments use a compatible Node.js version (currently `>=18.0.0 <26`) to avoid installation or runtime errors.
fix
Upgrade your Node.js runtime using a version manager like `nvm` (e.g., `nvm install 20 && nvm use 20`) or `volta` to a supported LTS version.
affects: >=2.0.0
gotchaCalling `workerPool.end()` immediately after queuing tasks, or while tasks are still executing, will cause any pending or in-progress task promises to be rejected. This can lead to unhandled promise rejections or incomplete operations.
fix
Always `await` the promises returned by `workerPool.single` or `workerPool.all` operations before calling `workerPool.end()` to ensure all tasks have a chance to complete. Implement `.catch()` for robust error handling on individual task promises.
affects: >=2.0.0
gotcha`gatsby-worker` is designed for CPU-bound tasks. Using worker threads for I/O-bound operations (e.g., heavy network requests, database queries that are already asynchronous) can introduce unnecessary overhead from serialization/deserialization and inter-process communication, potentially decreasing performance rather than improving it.
fix
Reserve `gatsby-worker` for truly CPU-intensive computations that block the event loop, such as image processing, complex data transformations, or heavy computations. For I/O, rely on Node.js's native asynchronous capabilities.
affects: >=2.0.0
gotchaThe primary API for `gatsby-worker` uses ES Module `import` syntax. Attempting to `require()` its named exports directly in a strict ES Module context will result in module resolution errors.
fix
Always use `import { SymbolName } from 'gatsby-worker'` for importing components like `WorkerPool`. If in a CommonJS environment, ensure your build setup correctly transpiles or bundles ES Modules. For worker paths, `require.resolve()` remains appropriate.
affects: >=2.0.0
Errors
Common errors & fixes
TypeError: (0 , gatsby_worker_1.WorkerPool) is not a constructor
Incorrect import syntax (often mixing CommonJS require with ES Module usage) or an environment mismatch where `gatsby-worker` is treated as CJS in an ESM context.
fix
Ensure your files are treated as ES Modules where `gatsby-worker` is imported and use `import { WorkerPool } from 'gatsby-worker';`. For `.js` files, this typically means having `"type": "module"` in your `package.json` or using `.mjs` file extensions.
The engine "node" is incompatible with this module. Expected version "X" Got "Y"
Your installed Node.js version does not meet the requirements specified in `gatsby-worker`'s `package.json` or Gatsby's overall compatibility policy.
fix
Update your Node.js version to one supported by Gatsby (e.g., using `nvm install --lts && nvm use --lts` or `volta install node@20`). Consult Gatsby's documentation for the most up-to-date Node.js support matrix.
Worker process exited with code 1
An uncaught error or exception occurred within one of your worker threads, causing the process to terminate prematurely. This could be due to a bug in the worker's logic, resource exhaustion, or an unhandled promise rejection.
fix
Set `silent: false` in the `WorkerPool` options to allow worker stdout/stderr to be logged to the parent process's console for debugging. Add robust `try/catch` blocks around your worker function logic and ensure all promises are handled to prevent uncaught rejections.
Upgrade
Version history
2.16.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
2 hits · last 30 days
node
2
Resources
gatsby-worker — npm install gatsby-worker · libregistry