Skip to content

File-Based Semaphore (TypeScript) / semats

Cross-platform file-based semaphore for process synchronization in Node.js.

Overview

File-Based Semaphore (TypeScript) provides a simple, reliable way to coordinate access to shared resources across multiple processes. It uses atomic file operations (temp file + rename) to prevent race conditions, making it perfect for build systems, CI/CD pipelines, and parallel workflows.

Status: Production Ready (v0.1.0)

Language: TypeScript

Repository: tuulbelt/file-based-semaphore-ts

Compatible with Rust Implementation

This tool uses the same lock file format as the Rust File-Based Semaphore, enabling cross-language process coordination.

Features

Atomic File Operations

Uses temp file + rename pattern for atomic lock creation, preventing race conditions.

Stale Lock Detection

Automatically detects and cleans orphaned locks from crashed processes using PID validation and timestamps.

CLI and Library API

Use from command line for shell scripts or import as a library for TypeScript/JavaScript applications.

Cross-Platform

Works on Linux, macOS, and Windows with consistent behavior.

Zero Runtime Dependencies

Uses only Node.js built-ins. No npm install required in production.

Comprehensive Security

Path traversal prevention, symlink resolution, tag sanitization, and cryptographic randomness for temp files.

Quick Start

bash
# Clone the repository
git clone https://github.com/tuulbelt/file-based-semaphore-ts.git
cd file-based-semaphore-ts

# Install dev dependencies (for TypeScript)
npm install

# Try to acquire a lock
semats try-acquire /tmp/my-lock.lock --tag "build process"

# Check lock status
semats status /tmp/my-lock.lock

# Release the lock
semats release /tmp/my-lock.lock

Use Cases

  • Build Systems: Prevent concurrent builds from conflicting
  • CI/CD Pipelines: Coordinate parallel test execution
  • Port Allocation: Lock ports before binding (used by port-conflict-resolver)
  • File Processing: Serialize access to shared files
  • Database Migrations: Ensure only one migration runs at a time

Why File-Based?

File-based locking provides several advantages:

  1. Simple: No external services or databases required
  2. Portable: Works everywhere - local, CI, containers
  3. Debuggable: Lock files are plain text - inspect with cat
  4. Cross-Language: Compatible with Rust sema tool
  5. Recoverable: Stale locks are automatically detected

Demo

See the tool in action:

File-Based Semaphore Demo

▶ View interactive recording on asciinema.org

Try it online:Open in StackBlitz

Run the tool directly in your browser with zero setup.

Demos are automatically generated via GitHub Actions when demo scripts are updated.

Next Steps

License

MIT License - see repository for details.

Released under the MIT License.