norutines
v0.4.3
Published
Lightweight Node.js concurrency library — routines and parallelism made simple.
Maintainers
Readme
Norutines 🧠⚙️
Librería de concurrencia ligera para Node.js basada en worker_threads.
Permite ejecutar funciones en paralelo de forma simple, confiable y sin dependencias externas.
🚀 Instalación
npm install norutinesO usando Yarn:
yarn add norutines🧩 Ejemplo básico
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)⚙️ API
| Método | Descripción |
|--------|--------------|
| routine(fn, ...args) | Ejecuta una función en un hilo separado y devuelve una Promise con el resultado. |
| spawn(fn, ...args) | Ejecuta una tarea en segundo plano sin bloquear el hilo principal. |
| defer(fn, ...args) | Alias de spawn, pensado para tareas que se ejecutan y olvidan. |
| 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 (spawn o defer) finalicen. |
| on(event, handler) | Escucha eventos internos del sistema de workers. |
| off(event, handler) | Detiene la escucha de eventos. |
🧠 Ejemplo con tareas paralelas
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)🛠️ Configuración del pool
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
})📊 Benchmark simple
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')🧹 Limpieza automática
Los workers se cierran automáticamente cuando están inactivos durante más de idleTimeout milisegundos.
Puedes ajustar este valor o desactivar el cierre automático estableciendo idleTimeout: 0.
🧾 Licencia
MIT License © 2025 — Luis Vilches
https://github.com/luisvilches/norutines
Norutines 🧠⚙️ (English Version)
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.
🚀 Installation
npm install norutinesor
yarn add norutines🧩 Basic Example
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)⚙️ API
| Method | Description |
|--------|--------------|
| routine(fn, ...args) | Executes a function in a separate thread and returns a Promise with the result. |
| spawn(fn, ...args) | Runs a background task without blocking the main thread. |
| defer(fn, ...args) | Alias for spawn, for fire-and-forget routines. |
| 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 (spawn / defer) tasks to finish. |
| on(event, handler) | Listens to internal worker events. |
| off(event, handler) | Stops listening to internal worker events. |
🧠 Parallel Example
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)🛠️ Worker Pool Configuration
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
})📊 Simple Benchmark
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')🧹 Automatic Cleanup
Workers are automatically terminated after being idle for more than idleTimeout milliseconds.
You can change this value or disable it by setting idleTimeout: 0.
🧾 License
MIT License © 2025 — Luis Vilches
https://github.com/luisvilches/norutines
