Lightweight Node.js concurrency library — routines and parallelism made simple.
npm install norutinesLibrería de concurrencia ligera para Node.js basada en worker_threads.
Permite ejecutar funciones en paralelo de forma simple, confiable y sin dependencias externas.
---
``bash`
npm install norutines
O usando Yarn:
`bash`
yarn add norutines
---
`js
import { routine } from 'norutines'
function heavyTask(n) {
let sum = 0
for (let i = 0; i < n; i++) sum += Math.sqrt(i)
return sum
}
const result = await routine(heavyTask, 1e8)
console.log('✅ Resultado:', result)
`
---
| Método | Descripción |
|--------|--------------|
| routine(fn, ...args) | Ejecuta una función en un hilo separado y devuelve una Promise con el resultado. |spawn
| spawn(fn, ...args) | Ejecuta una tarea en segundo plano sin bloquear el hilo principal. |
| defer(fn, ...args) | Alias de , pensado para tareas que se ejecutan y olvidan. |spawn
| parallel(tasks) | Ejecuta varias tareas en paralelo y devuelve un array con los resultados. |
| module(path) | Importa un módulo dentro del worker y ejecuta sus métodos en paralelo. |
| configurePool(options) | Configura el pool de workers (tamaño, timeout, debug, etc.). |
| stats() | Retorna estadísticas del pool actual (workers activos, en cola, etc.). |
| setDebug(true/false) | Activa o desactiva el modo debug para ver el código enviado a los workers. |
| waitAll() | Espera que todas las tareas en segundo plano ( o defer) finalicen. |
| on(event, handler) | Escucha eventos internos del sistema de workers. |
| off(event, handler) | Detiene la escucha de eventos. |
---
`js
import { parallel } from 'norutines'
function calc(n) {
let sum = 0
for (let i = 0; i < n; i++) sum += Math.sqrt(i)
return sum
}
const results = await parallel([
[calc, 1e7],
[calc, 2e7],
[calc, 3e7]
])
console.log(results)
`
---
`js
import { configurePool } from 'norutines'
configurePool({
size: 'auto', // Número de workers (auto usa núcleos-1)
idleTimeout: 2000, // Tiempo en ms para cerrar workers inactivos
maxQueue: 1000, // Máximo de tareas en espera
debug: false // Modo debug
})
`
---
`js
import { routine, parallel } from 'norutines'
function heavy(n) {
let s = 0
for (let i = 0; i < n; i++) s += Math.sqrt(i)
return s
}
const N = 1e8
console.time('Sequential')
for (let i = 0; i < 4; i++) heavy(N)
console.timeEnd('Sequential')
console.time('Parallel')
await parallel([[heavy, N], [heavy, N], [heavy, N], [heavy, N]])
console.timeEnd('Parallel')
`
---
Los workers se cierran automáticamente cuando están inactivos durante más de idleTimeout milisegundos. idleTimeout: 0
Puedes ajustar este valor o desactivar el cierre automático estableciendo .
---
MIT License © 2025 — Luis Vilches
https://github.com/luisvilches/norutines
---
---
Lightweight concurrency library for Node.js built on top of worker_threads.
Allows you to execute functions in parallel threads easily and safely, without external dependencies.
---
`bash`
npm install norutines
or
`bash`
yarn add norutines
---
`js
import { routine } from 'norutines'
function heavyTask(n) {
let sum = 0
for (let i = 0; i < n; i++) sum += Math.sqrt(i)
return sum
}
const result = await routine(heavyTask, 1e8)
console.log('✅ Result:', result)
`
---
| Method | Description |
|--------|--------------|
| routine(fn, ...args) | Executes a function in a separate thread and returns a Promise with the result. |spawn
| spawn(fn, ...args) | Runs a background task without blocking the main thread. |
| defer(fn, ...args) | Alias for , for fire-and-forget routines. |spawn
| parallel(tasks) | Runs multiple tasks in parallel and returns an array with all results. |
| module(path) | Loads a module inside the worker and executes its methods in parallel. |
| configurePool(options) | Configures the worker pool (size, timeout, debug, etc.). |
| stats() | Returns the current worker pool statistics. |
| setDebug(true/false) | Enables or disables debug mode to inspect the code sent to workers. |
| waitAll() | Waits for all background ( / defer) tasks to finish. |
| on(event, handler) | Listens to internal worker events. |
| off(event, handler) | Stops listening to internal worker events. |
---
`js
import { parallel } from 'norutines'
function calc(n) {
let sum = 0
for (let i = 0; i < n; i++) sum += Math.sqrt(i)
return sum
}
const results = await parallel([
[calc, 1e7],
[calc, 2e7],
[calc, 3e7]
])
console.log(results)
`
---
`js
import { configurePool } from 'norutines'
configurePool({
size: 'auto', // Number of workers (auto = CPU cores - 1)
idleTimeout: 2000, // Time in ms before idle workers are closed
maxQueue: 1000, // Maximum queued tasks
debug: false // Debug mode
})
`
---
`js
import { routine, parallel } from 'norutines'
function heavy(n) {
let s = 0
for (let i = 0; i < n; i++) s += Math.sqrt(i)
return s
}
const N = 1e8
console.time('Sequential')
for (let i = 0; i < 4; i++) heavy(N)
console.timeEnd('Sequential')
console.time('Parallel')
await parallel([[heavy, N], [heavy, N], [heavy, N], [heavy, N]])
console.timeEnd('Parallel')
`
---
Workers are automatically terminated after being idle for more than idleTimeout milliseconds. idleTimeout: 0`.
You can change this value or disable it by setting
---
MIT License © 2025 — Luis Vilches
https://github.com/luisvilches/norutines