easy-node-threading
v1.0.9
Published
⚡ Run JavaScript functions or files in isolated Node.js worker threads with a single call. Simple, minimal, and modern.
Maintainers
Readme
easy-node-threading
- ⚡ Run JavaScript functions or files in isolated Node.js worker threads with a single call. Simple, minimal, and modern.
- ♻️ Works seamlessly with
CommonJS,ESMandTypeScript
🤔 Why easy-node-threading is great
- Zero boilerplate: Run any function or file in a worker thread with a single call. No manual
Workersetup needed. - Isolated execution: Heavy computations run in a separate thread, keeping your main Node.js event loop fast and responsive.
- Flexible & modern: Supports both function references and file paths,
ESMorCJS, and optional logging. - Full Node.js WorkerOptions support: You can pass resource limits,
execArgv,env,stdioand everything Node’s worker API allows. - Lightweight & minimal: Tiny wrapper, no unnecessary dependencies.
📦 Install via NPM
$ npm i easy-node-threading💻 Usage
- See examples below for each scenario!
- For file tasks, always convert the path to a file URL using
pathToFileURLfor ESM compatibility. - By default,
showLogs = trueprints both parent and worker messages. Set it tofalseto silence logs. - For
workerOptionsobject param, please see the list of available options here ➡ 🔗 https://nodejs.org/api/worker_threads.html#new-workerfilename-options
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| task | Function or string | — | The function to execute in the worker, or a path/URL to a JavaScript file. |
| workerOptions | Object | {} | Optional options passed directly to the Node.js Worker constructor (e.g., resourceLimits, execArgv). |
| showLogs | boolean | true | Whether to log messages from the parent and worker threads to the console. Set to false to hide logs. |
CommonJS
Task file example
// task.js (CommonJS)
module.exports = async () => {
console.log('Running heavy calculation inside the worker...');
let sum = 0;
for (let i = 0; i < 1e7; i++) {
sum += i;
}
return sum;
};How to use in CommonJS
const easyNodeThreading = require('easy-node-threading');
const options = {
// --| workerOptions here
resourceLimits: {
maxOldGenerationSizeMb: 64, // --| Limit memory usage
codeRangeSizeMb: 4
},
execArgv: ['--trace-warnings'], // --| Node.js flags for worker
env: { NODE_ENV: 'worker' } // --| Set environment
};
(async () => {
const result = await easyNodeThreading(
'./task.js', // --| File to run
options, // --| Worker options object
true // --| Show logs
);
console.log('File task result:', result);
// --| Or use a function directly from here, rather than an external file
const resultFromFunction = await easyNodeThreading(taskFunction, {}, false);
console.log('Function task result:', resultFromFunction);
})();
const taskFunction = () => {
let sum = 0;
for (let i = 0; i < 1e7; i++) {
sum += i;
}
return sum;
};ESM
Task file example
// --| task.mjs (ESM)
export default async () => {
console.log('Running heavy calculation inside the worker...');
let sum = 0;
for (let i = 0; i < 1e7; i++) {
sum += i;
}
return sum;
};How to use in ESM
import easyNodeThreading from 'easy-node-threading';
const options = {
// --| workerOptions here
resourceLimits: {
maxOldGenerationSizeMb: 64, // --| Limit memory usage
codeRangeSizeMb: 4
},
execArgv: ['--trace-warnings'], // --| Node.js flags for worker
env: { NODE_ENV: 'worker' } // --| Set environment
};
(async () => {
const result = await easyNodeThreading(
'./task.mjs', // --| File to run
options, // --| Worker options object
true // --| Show logs
);
console.log('File task result:', result);
// --| Or use a function directly from here, rather than an external file
const resultFromFunction = await easyNodeThreading(taskFunction, {}, false);
console.log('Function task result:', resultFromFunction);
})();
const taskFunction = () => {
let sum = 0;
for (let i = 0; i < 1e7; i++) {
sum += i;
}
return sum;
};TypeScript
Task file example - Note we are using the same ".mjs" extension to avoid complications
// --| task.mjs (ESM)
export default async () => {
console.log('Running heavy calculation inside the worker...');
let sum = 0;
for (let i = 0; i < 1e7; i++) {
sum += i;
}
return sum;
};How to use in TypeScript
import easyNodeThreading from 'easy-node-threading';
import { WorkerOptions } from 'node:worker_threads';
const taskFunction = (): number => {
let sum = 0;
for (let i = 0; i < 1e7; i++) {
sum += i;
}
return sum;
};
const options: WorkerOptions = {
// --| workerOptions here
resourceLimits: {
maxOldGenerationSizeMb: 64, // --| Limit memory usage
codeRangeSizeMb: 4
},
execArgv: ['--trace-warnings'], // --| Node.js flags for worker
env: { NODE_ENV: 'worker' } // --| Set environment
};
(async () => {
const result = await easyNodeThreading(
'./task.mjs', // --| File to run (NOTICE WE RUNNING A .mjs EXTENSION!)
options, // --| Worker options object
true // --| Show logs
);
console.log('File task result:', result);
// --| Or use a function directly from here, rather than an external file
const resultFromFunction = await easyNodeThreading(taskFunction, {}, false);
console.log('Function task result:', resultFromFunction);
})();Run multiple workers in parallel. This example can be used in CommonJS, ESM and TypeScript
// --| Example function tasks
const task1 = () => {
let sum = 0;
for (let i = 0; i < 1e7; i++) {
sum += i;
}
return `Task1 result: ${sum}`;
};
const task2 = () => {
let product = 1;
for (let i = 1; i <= 10; i++) {
product *= i;
}
return `Task2 result: ${product}`;
};
const task3 = () => `Task3 message at ${new Date().toISOString()}`;
(async () => {
// --| Start 3 workers in parallel
const workers = [
easyNodeThreading(task1, {}, true),
easyNodeThreading(task2, {}, true),
easyNodeThreading(task3, {}, true)
];
// --| Wait for all workers to complete
const results = await Promise.all(workers);
console.log('All worker results:');
results.forEach(result => console.log(result));
})();