Skip to content

Singh1106/noderoutine

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

NodeRoutine

A lightweight library that brings Go-like goroutines to Node.js using Worker Threads for easy concurrency management.

Installation

npm install noderoutine

Features

  • 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

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);

API

nodeRoutine(fn, ...args)

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

setMaxThreads(limit)

Sets the maximum number of concurrent threads.

  • limit: The new thread limit (must be a positive number)

getMaxThreads()

Gets the current maximum thread limit.

  • Returns: The current thread limit

getActiveThreads()

Gets the current number of active threads.

  • Returns: The current number of active threads

getQueueLength()

Gets the current number of queued tasks.

  • Returns: The current queue length

Security Considerations

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.

License

MIT

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors