Concurrency Semaphore for Node.js

1.1.0 · abandoned · verified Sun Apr 19

This package provides a basic counting semaphore mechanism for Node.js environments, designed to limit the number of concurrent operations accessing a shared resource. The current and only stable version, 1.1.0, was published 9 years ago and explicitly targets Node.js 0.8.0. Due to its age and lack of maintenance, it does not follow a regular release cadence and is effectively abandoned for modern Node.js development. Its primary differentiator is its extreme simplicity and minimal footprint, offering fundamental concurrency control without features found in more contemporary, promise-based semaphore implementations (e.g., `async-sema`, `await-semaphore`). While functional for very old projects, it lacks modern JavaScript features and type definitions out of the box.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a semaphore to limit simultaneous database access within a Node.js HTTP server. It shows taking and leaving the semaphore using its callback-based API.

const semaphore = require('semaphore');
const http = require('http');

// Limit concurrent database access to 1 operation at a time
const dbSemaphore = semaphore(1);

const expensive_database_operation = (callback) => {
  console.log('Starting expensive DB operation...');
  setTimeout(() => {
    const error = Math.random() > 0.8 ? new Error('Database error!') : null;
    console.log('Finished expensive DB operation.');
    callback(error, 'Data from DB');
  }, 1000);
};

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  dbSemaphore.take(function() {
    console.log('Semaphore taken, requesting DB operation...');
    expensive_database_operation(function(err, data) {
      dbSemaphore.leave();
      if (err) {
        console.error('Request failed:', err.message);
        return res.end(`Error: ${err.message}`);
      }
      res.end(`Success: ${data}`);
    });
  });
});

const PORT = process.env.PORT ?? 3000;
server.listen(PORT, () => {
  console.log(`Server listening on http://localhost:${PORT}`);
  console.log('Try opening multiple tabs to http://localhost:3000 to see concurrency limits in action.');
});

view raw JSON →