A lightweight library that brings Go-like goroutines to Node.js using Worker Threads for easy concurrency management.
npm install noderoutine- Run functions in separate worker threads with a simple API
- Automatic queue management for concurrent tasks
- Configurable concurrency limits
- Promise-based interface for easy async/await usage
import { nodeRoutine, setMaxThreads } from "noderoutine";
// Optional: Set the maximum number of concurrent threads (default is 20)
setMaxThreads(10);
// Example: Run CPU-intensive tasks in worker threads
async function main() {
// Define a CPU-intensive function
function calculatePrimes(max) {
const primes = [];
for (let i = 2; i <= max; i++) {
let isPrime = true;
for (let j = 2; j <= Math.sqrt(i); j++) {
if (i % j === 0) {
isPrime = false;
break;
}
}
if (isPrime) primes.push(i);
}
return primes;
}
// Run multiple CPU-intensive tasks concurrently
const results = await Promise.all([
nodeRoutine(calculatePrimes, 50000),
nodeRoutine(calculatePrimes, 40000),
nodeRoutine(calculatePrimes, 30000),
nodeRoutine(calculatePrimes, 20000),
]);
console.log(`Found ${results[0].length} primes up to 50000`);
console.log(`Found ${results[1].length} primes up to 40000`);
console.log(`Found ${results[2].length} primes up to 30000`);
console.log(`Found ${results[3].length} primes up to 20000`);
}
main().catch(console.error);Runs a function in a separate worker thread.
fn: Function to execute in the worker thread...args: Arguments to pass to the function- Returns: Promise resolving to the function's return value
Sets the maximum number of concurrent threads.
limit: The new thread limit (must be a positive number)
Gets the current maximum thread limit.
- Returns: The current thread limit
Gets the current number of active threads.
- Returns: The current number of active threads
Gets the current number of queued tasks.
- Returns: The current queue length
This library uses new Function() to deserialize functions in worker threads. Be cautious about running untrusted code as this could potentially lead to code injection vulnerabilities.
MIT