or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-supervisor

A supervisor program for running and monitoring Node.js applications with automatic restart capabilities

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/supervisor@0.12.x

To install, run

npx @tessl/cli install tessl/npm-supervisor@0.12.0

index.mddocs/

Supervisor

Supervisor is a Node.js utility that monitors and automatically restarts applications when they crash or when source files change. It provides hot-code reloading functionality without memory leaks by completely restarting the process rather than using module reloading.

Package Information

  • Package Name: supervisor
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install supervisor -g

Core Imports

As a library:

const supervisor = require("supervisor");

As a CLI tool (global installation):

supervisor myapp.js
# or
node-supervisor myapp.js

Basic Usage

const supervisor = require("supervisor");

// Run supervisor programmatically
supervisor.run(["--watch", "src", "--extensions", "js,json", "app.js"]);

CLI usage:

# Basic supervision
supervisor myapp.js

# Watch specific directories and extensions
supervisor --watch src --extensions js,json myapp.js

# Debug mode with custom port
supervisor --debug=5858 myapp.js

# Non-interactive mode for production
supervisor --non-interactive --no-restart-on error myapp.js

Architecture

Supervisor operates using several key components:

  • Process Management: Spawns and monitors child processes using Node.js child_process.spawn
  • File Watching: Uses fs.watchFile or fs.watch to monitor file changes across directories
  • Signal Handling: Intercepts and forwards system signals (SIGTERM, SIGINT, etc.) to child processes
  • Command-Line Interface: Comprehensive CLI with extensive configuration options
  • Interactive Mode: Allows manual restarts via "rs" command in stdin

Capabilities

Main API Function

Primary function for starting supervisor programmatically.

/**
 * Start supervisor with command-line arguments
 * @param {string[]} args - Array of command-line arguments
 */
function run(args);

Usage Example:

const supervisor = require("supervisor");

// Start with file watching
supervisor.run([
  "--watch", "src,config",
  "--extensions", "js,json,yaml", 
  "--ignore", "node_modules,logs",
  "server.js"
]);

Child Process Access

Access to the currently running supervised process.

/**
 * Reference to the current child process
 * @type {ChildProcess|null}
 */
supervisor.child;

Usage Example:

const supervisor = require("supervisor");

// Start supervisor
supervisor.run(["app.js"]);

// Access child process (after it starts)
setTimeout(() => {
  if (supervisor.child) {
    console.log("Child PID:", supervisor.child.pid);
    // Send custom signal
    supervisor.child.kill("SIGUSR1");
  }
}, 1000);

Command-Line Interface

Comprehensive CLI for running supervisor as a command-line tool.

supervisor [options] <program>
supervisor [options] -- <program> [args...]

Core Options

Program and Execution:

  • <program> - The program to run (required)
  • -x, --exec <executable> - Executable to run the program (default: 'node')

File Watching:

  • -w, --watch <watchItems> - Comma-delimited list of folders/files to watch (default: '.')
  • -i, --ignore <ignoreItems> - Comma-delimited list of folders to ignore
  • -e, --extensions <extensions> - File extensions to watch (default: 'node,js')
  • -p, --poll-interval <ms> - File polling interval in milliseconds
  • --ignore-symlinks - Ignore symbolic links when watching
  • --force-watch - Use fs.watch instead of fs.watchFile

Process Control:

  • -n, --no-restart-on <condition> - Don't restart on 'error'|'exit'|'success'
  • -t, --non-interactive - Disable interactive stdin listening
  • -k, --instant-kill - Use SIGKILL instead of SIGTERM for termination
  • --save-pid <path> - Save supervisor's PID to file

Debug and Development:

  • --debug[=port] - Start with --debug flag
  • --debug-brk[=port] - Start with --debug-brk flag
  • --harmony - Start with --harmony flag
  • --inspect - Start with --inspect flag
  • --harmony_default_parameters - Enable harmony default parameters
  • --harmony_destructuring - Enable harmony destructuring

Output and Logging:

  • -q, --quiet - Suppress debug messages
  • -V, --verbose - Show extra debug messages
  • -s, --timestamp - Log timestamp after each run
  • -RV, --restart-verbose - Log files that cause restarts

Help:

  • -h, --help, -? - Display usage instructions

Interactive Commands

When running in interactive mode (default), supervisor accepts these stdin commands:

rs  # Restart the supervised process manually

Usage Examples:

# Basic usage
supervisor myapp.js

# CoffeeScript support
supervisor myapp.coffee

# Custom executable and extensions  
supervisor -x coffee -e coffee,js myapp.coffee

# Production setup with specific watching
supervisor --watch lib,config --ignore logs,tmp --non-interactive server.js

# Debug mode
supervisor --debug=5858 --harmony myapp.js

# Full configuration example
supervisor \
  --watch src,config \
  --ignore node_modules,logs,tmp \
  --extensions js,json,yaml \
  --poll-interval 2000 \
  --no-restart-on error \
  --save-pid /var/run/myapp.pid \
  --timestamp \
  -- server.js --port 3000 --env production

File Watching Behavior

Extensions and Patterns

  • Default Extensions: node,js
  • CoffeeScript Detection: Automatically adds coffee,litcoffee when program has .coffee extension
  • Custom Extensions: Specify via -e, --extensions option
  • Pattern Matching: Uses RegExp matching against file extensions

Watching Strategy

  • Default: Uses fs.watchFile for cross-platform compatibility
  • Windows Optimization: Uses fs.watch on Windows Node.js ≤ 0.6
  • Force Watch: --force-watch forces fs.watch usage
  • Polling: Configurable via --poll-interval (default: 1000ms)

Ignore Patterns

  • Directory Ignoring: Specified directories and their subdirectories are completely ignored
  • Symlink Handling: Use --ignore-symlinks to skip symbolic links
  • Path Resolution: All ignore paths are resolved to absolute paths

Signal Handling

Supervisor handles these system signals and forwards them to the child process:

// Handled signals (Unix/Linux)
SIGTERM  // Graceful termination
SIGINT   // Interrupt (Ctrl+C)
SIGHUP   // Hangup
SIGQUIT  // Quit signal

Behavior:

  • Signals are intercepted by supervisor
  • Forwarded to child process
  • Supervisor exits after child terminates
  • Windows: Limited signal support (handled gracefully)

Process Lifecycle

Startup Sequence

  1. Parse command-line arguments
  2. Configure file watching patterns
  3. Set up signal handlers
  4. Start child process
  5. Initialize file watchers
  6. Enter interactive mode (if enabled)

Restart Triggers

  • File Changes: Modified files matching watch patterns
  • Process Crash: Child process exits (unless disabled)
  • Manual Restart: "rs" command in interactive mode
  • Signal Handling: Forwarded system signals

Shutdown Sequence

  1. Receive termination signal
  2. Forward signal to child process
  3. Wait for child termination
  4. Clean up watchers and resources
  5. Remove PID file (if configured)
  6. Exit supervisor process

Error Handling

Common Exit Codes

  • 0: Clean exit
  • Non-zero: Application error (triggers restart unless configured otherwise)

No-Restart Conditions

  • --no-restart-on error: Don't restart on non-zero exit codes
  • --no-restart-on exit: Don't restart regardless of exit code
  • --no-restart-on success: Don't restart only on zero exit codes

Error Scenarios

  • ENOENT: Missing executable (Windows: tries .cmd extension)
  • EACCES: Permission denied for PID file
  • EISDIR: PID file path is directory
  • File Watch Errors: Logged but don't stop supervision

Platform Considerations

Windows Support

  • Executable Detection: Automatically tries .cmd extension for missing executables
  • Signal Limitations: Limited signal support handled gracefully
  • File Watching: Optimized strategy for Windows systems
  • Path Handling: Uses Windows-appropriate path separators

Unix/Linux Support

  • Full Signal Support: All POSIX signals handled properly
  • Symlink Support: Can follow or ignore symlinks as configured
  • File Permissions: Respects Unix file permissions

Dependencies

Core Node.js Modules:

  • fs - File system operations
  • child_process - Process spawning (spawn function)
  • path - Path manipulation utilities

External Dependencies:

  • None (pure Node.js implementation)

Performance Characteristics

  • Memory Efficient: Full process restart prevents memory leaks
  • File Watching: Configurable polling intervals for performance tuning
  • Process Overhead: Minimal - just file watching and process management
  • Startup Time: Fast initialization with lazy file discovery