A supervisor program for running and monitoring Node.js applications with automatic restart capabilities
npx @tessl/cli install tessl/npm-supervisor@0.12.00
# Supervisor
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: supervisor
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install supervisor -g`
10
11
## Core Imports
12
13
As a library:
14
15
```javascript
16
const supervisor = require("supervisor");
17
```
18
19
As a CLI tool (global installation):
20
21
```bash
22
supervisor myapp.js
23
# or
24
node-supervisor myapp.js
25
```
26
27
## Basic Usage
28
29
```javascript
30
const supervisor = require("supervisor");
31
32
// Run supervisor programmatically
33
supervisor.run(["--watch", "src", "--extensions", "js,json", "app.js"]);
34
```
35
36
CLI usage:
37
38
```bash
39
# Basic supervision
40
supervisor myapp.js
41
42
# Watch specific directories and extensions
43
supervisor --watch src --extensions js,json myapp.js
44
45
# Debug mode with custom port
46
supervisor --debug=5858 myapp.js
47
48
# Non-interactive mode for production
49
supervisor --non-interactive --no-restart-on error myapp.js
50
```
51
52
## Architecture
53
54
Supervisor operates using several key components:
55
56
- **Process Management**: Spawns and monitors child processes using Node.js child_process.spawn
57
- **File Watching**: Uses fs.watchFile or fs.watch to monitor file changes across directories
58
- **Signal Handling**: Intercepts and forwards system signals (SIGTERM, SIGINT, etc.) to child processes
59
- **Command-Line Interface**: Comprehensive CLI with extensive configuration options
60
- **Interactive Mode**: Allows manual restarts via "rs" command in stdin
61
62
## Capabilities
63
64
### Main API Function
65
66
Primary function for starting supervisor programmatically.
67
68
```javascript { .api }
69
/**
70
* Start supervisor with command-line arguments
71
* @param {string[]} args - Array of command-line arguments
72
*/
73
function run(args);
74
```
75
76
**Usage Example:**
77
78
```javascript
79
const supervisor = require("supervisor");
80
81
// Start with file watching
82
supervisor.run([
83
"--watch", "src,config",
84
"--extensions", "js,json,yaml",
85
"--ignore", "node_modules,logs",
86
"server.js"
87
]);
88
```
89
90
### Child Process Access
91
92
Access to the currently running supervised process.
93
94
```javascript { .api }
95
/**
96
* Reference to the current child process
97
* @type {ChildProcess|null}
98
*/
99
supervisor.child;
100
```
101
102
**Usage Example:**
103
104
```javascript
105
const supervisor = require("supervisor");
106
107
// Start supervisor
108
supervisor.run(["app.js"]);
109
110
// Access child process (after it starts)
111
setTimeout(() => {
112
if (supervisor.child) {
113
console.log("Child PID:", supervisor.child.pid);
114
// Send custom signal
115
supervisor.child.kill("SIGUSR1");
116
}
117
}, 1000);
118
```
119
120
### Command-Line Interface
121
122
Comprehensive CLI for running supervisor as a command-line tool.
123
124
```bash { .api }
125
supervisor [options] <program>
126
supervisor [options] -- <program> [args...]
127
```
128
129
#### Core Options
130
131
**Program and Execution:**
132
- `<program>` - The program to run (required)
133
- `-x, --exec <executable>` - Executable to run the program (default: 'node')
134
135
**File Watching:**
136
- `-w, --watch <watchItems>` - Comma-delimited list of folders/files to watch (default: '.')
137
- `-i, --ignore <ignoreItems>` - Comma-delimited list of folders to ignore
138
- `-e, --extensions <extensions>` - File extensions to watch (default: 'node,js')
139
- `-p, --poll-interval <ms>` - File polling interval in milliseconds
140
- `--ignore-symlinks` - Ignore symbolic links when watching
141
- `--force-watch` - Use fs.watch instead of fs.watchFile
142
143
**Process Control:**
144
- `-n, --no-restart-on <condition>` - Don't restart on 'error'|'exit'|'success'
145
- `-t, --non-interactive` - Disable interactive stdin listening
146
- `-k, --instant-kill` - Use SIGKILL instead of SIGTERM for termination
147
- `--save-pid <path>` - Save supervisor's PID to file
148
149
**Debug and Development:**
150
- `--debug[=port]` - Start with --debug flag
151
- `--debug-brk[=port]` - Start with --debug-brk flag
152
- `--harmony` - Start with --harmony flag
153
- `--inspect` - Start with --inspect flag
154
- `--harmony_default_parameters` - Enable harmony default parameters
155
- `--harmony_destructuring` - Enable harmony destructuring
156
157
**Output and Logging:**
158
- `-q, --quiet` - Suppress debug messages
159
- `-V, --verbose` - Show extra debug messages
160
- `-s, --timestamp` - Log timestamp after each run
161
- `-RV, --restart-verbose` - Log files that cause restarts
162
163
**Help:**
164
- `-h, --help, -?` - Display usage instructions
165
166
#### Interactive Commands
167
168
When running in interactive mode (default), supervisor accepts these stdin commands:
169
170
```bash { .api }
171
rs # Restart the supervised process manually
172
```
173
174
**Usage Examples:**
175
176
```bash
177
# Basic usage
178
supervisor myapp.js
179
180
# CoffeeScript support
181
supervisor myapp.coffee
182
183
# Custom executable and extensions
184
supervisor -x coffee -e coffee,js myapp.coffee
185
186
# Production setup with specific watching
187
supervisor --watch lib,config --ignore logs,tmp --non-interactive server.js
188
189
# Debug mode
190
supervisor --debug=5858 --harmony myapp.js
191
192
# Full configuration example
193
supervisor \
194
--watch src,config \
195
--ignore node_modules,logs,tmp \
196
--extensions js,json,yaml \
197
--poll-interval 2000 \
198
--no-restart-on error \
199
--save-pid /var/run/myapp.pid \
200
--timestamp \
201
-- server.js --port 3000 --env production
202
```
203
204
## File Watching Behavior
205
206
### Extensions and Patterns
207
208
- **Default Extensions**: `node,js`
209
- **CoffeeScript Detection**: Automatically adds `coffee,litcoffee` when program has .coffee extension
210
- **Custom Extensions**: Specify via `-e, --extensions` option
211
- **Pattern Matching**: Uses RegExp matching against file extensions
212
213
### Watching Strategy
214
215
- **Default**: Uses fs.watchFile for cross-platform compatibility
216
- **Windows Optimization**: Uses fs.watch on Windows Node.js ≤ 0.6
217
- **Force Watch**: `--force-watch` forces fs.watch usage
218
- **Polling**: Configurable via `--poll-interval` (default: 1000ms)
219
220
### Ignore Patterns
221
222
- **Directory Ignoring**: Specified directories and their subdirectories are completely ignored
223
- **Symlink Handling**: Use `--ignore-symlinks` to skip symbolic links
224
- **Path Resolution**: All ignore paths are resolved to absolute paths
225
226
## Signal Handling
227
228
Supervisor handles these system signals and forwards them to the child process:
229
230
```javascript { .api }
231
// Handled signals (Unix/Linux)
232
SIGTERM // Graceful termination
233
SIGINT // Interrupt (Ctrl+C)
234
SIGHUP // Hangup
235
SIGQUIT // Quit signal
236
```
237
238
**Behavior:**
239
- Signals are intercepted by supervisor
240
- Forwarded to child process
241
- Supervisor exits after child terminates
242
- Windows: Limited signal support (handled gracefully)
243
244
## Process Lifecycle
245
246
### Startup Sequence
247
248
1. Parse command-line arguments
249
2. Configure file watching patterns
250
3. Set up signal handlers
251
4. Start child process
252
5. Initialize file watchers
253
6. Enter interactive mode (if enabled)
254
255
### Restart Triggers
256
257
- **File Changes**: Modified files matching watch patterns
258
- **Process Crash**: Child process exits (unless disabled)
259
- **Manual Restart**: "rs" command in interactive mode
260
- **Signal Handling**: Forwarded system signals
261
262
### Shutdown Sequence
263
264
1. Receive termination signal
265
2. Forward signal to child process
266
3. Wait for child termination
267
4. Clean up watchers and resources
268
5. Remove PID file (if configured)
269
6. Exit supervisor process
270
271
## Error Handling
272
273
### Common Exit Codes
274
275
- **0**: Clean exit
276
- **Non-zero**: Application error (triggers restart unless configured otherwise)
277
278
### No-Restart Conditions
279
280
- `--no-restart-on error`: Don't restart on non-zero exit codes
281
- `--no-restart-on exit`: Don't restart regardless of exit code
282
- `--no-restart-on success`: Don't restart only on zero exit codes
283
284
### Error Scenarios
285
286
- **ENOENT**: Missing executable (Windows: tries .cmd extension)
287
- **EACCES**: Permission denied for PID file
288
- **EISDIR**: PID file path is directory
289
- **File Watch Errors**: Logged but don't stop supervision
290
291
## Platform Considerations
292
293
### Windows Support
294
295
- **Executable Detection**: Automatically tries .cmd extension for missing executables
296
- **Signal Limitations**: Limited signal support handled gracefully
297
- **File Watching**: Optimized strategy for Windows systems
298
- **Path Handling**: Uses Windows-appropriate path separators
299
300
### Unix/Linux Support
301
302
- **Full Signal Support**: All POSIX signals handled properly
303
- **Symlink Support**: Can follow or ignore symlinks as configured
304
- **File Permissions**: Respects Unix file permissions
305
306
## Dependencies
307
308
**Core Node.js Modules:**
309
- `fs` - File system operations
310
- `child_process` - Process spawning (spawn function)
311
- `path` - Path manipulation utilities
312
313
**External Dependencies:**
314
- None (pure Node.js implementation)
315
316
## Performance Characteristics
317
318
- **Memory Efficient**: Full process restart prevents memory leaks
319
- **File Watching**: Configurable polling intervals for performance tuning
320
- **Process Overhead**: Minimal - just file watching and process management
321
- **Startup Time**: Fast initialization with lazy file discovery