A Node.js test application demonstrating the forever-monitor NPM package's automatic process restart capabilities. This project creates a simple HTTP server that deliberately exits to showcase how forever-monitor detects crashes and restarts the process automatically.
Built in November 2020. This application helps developers understand how to implement automatic process restart and recovery in Node.js applications.
- 🔄 Automatic process restart on crash/exit
- 📊 Restart counter tracking
- 🎯 Configurable restart limits
- 🚦 Exit code-based restart control
- ⚙️ Simple HTTP server for testing
- 📝 Error handling and logging
- Automatic Process Restart: Automatically recovers from crashes and exits.
- Restart Counter Tracking: Monitors and injects the number of restarts into the child process.
- Configurable Limits: Easily adjust maximum restart attempts and monitoring behavior.
- Exit Code Logic: Intelligent handling of different exit codes for granular control.
- Process Supervision: Implements a robust supervisor-worker architecture.
- Decoupled Design: Separates monitoring logic from application business logic.
- Resource Efficiency: Minimal overhead for the supervisor process.
- Error Handling: Graceful termination and error reporting using specialized libraries.
- Simple Setup: Minimal configuration required to get started.
- Integrated Debugging: Built-in support for Node.js inspector and debug mode.
- Clear Documentation: Detailed architecture diagrams and process flow explanations.
- Environment Aware: Configurable settings for different deployment scenarios.
- Node.js (v8 or higher)
- npm or yarn
- Clone the repository:
git clone https://github.com/orassayag/node-test-restart.git
cd node-test-restart- Install dependencies:
npm installRun the monitor to see automatic restarts in action:
npm startThe primary way to run the application is through the monitor:
npm startTo stop all Node.js processes (especially useful on Windows):
npm run stopTo run the server in debug mode without the monitor:
npm run debugThe server will:
- Start on port 3001
- Exit after 1 second with code 2
- Automatically restart (up to 10 times)
- Display restart count each time
graph TD
A[npm start] --> B[monitor.js]
B --> C[Forever Monitor]
C --> D[Start server.js]
D --> E[HTTP Server Running]
E --> F[Server exits after 1s]
F --> G{Exit Code?}
G -->|Code 1| H[Stop - No Restart]
G -->|Code 2| I{Max Restarts?}
I -->|Not Reached| J[Increment Counter]
J --> D
I -->|Reached| K[Stop Monitor]
style A fill:#e1f5ff
style C fill:#fff3cd
style E fill:#d4edda
style H fill:#f8d7da
style K fill:#f8d7da
- Monitor Initialization:
monitor.jscreates a forever-monitor instance - Server Start: Monitor spawns
server.jsprocess - HTTP Server: Server listens on configured port (default: 3001)
- Deliberate Exit: After 1 second, server exits with code 2
- Monitor Detection: Forever-monitor detects the exit
- Restart Decision: Based on exit code and restart count
- Process Restart: Monitor restarts the server with incremented counter
- Repeat: Process continues until max restarts reached
| Exit Code | Behavior |
|---|---|
| 1 | Monitor stops - no restart |
| 2 or other | Monitor restarts process automatically |
| Max reached | Monitor stops regardless of exit code |
- Resilience by Design: The system assumes processes will fail and provides an automated recovery path.
- Single Responsibility: The monitor manages process lifecycle, while the server handles application logic.
- Observability: Every restart and exit event is captured and logged for analysis.
- Configurability: All operational parameters are externalized from the core logic.
- Supervisor Pattern: A dedicated process monitors the health of worker processes and restarts them on failure.
- Worker Process: The application logic runs in a sandboxed child process.
- Singleton Configuration: Centralized settings management ensures consistency across the application.
Edit src/settings/settings.js:
const settings = {
NODE_ENV: 'development', // Environment mode
SERVER_PORT: '3001', // HTTP server port
};Edit src/monitor.js:
const child = new forever.Monitor('server.js', {
max: 10, // Maximum number of restarts
silent: false, // Show/hide output
args: [restartCount], // Arguments passed to server
});npm startStarts the forever-monitor which automatically restarts the server.
npm run stopForcefully stops all Node.js processes using taskkill.
npm run debugStarts the server with Node.js inspector for debugging.
node-test-restart/
├── src/
│ ├── monitor.js # Forever-monitor configuration
│ ├── server.js # HTTP server (exits deliberately)
│ ├── settings/
│ │ └── settings.js # Configuration settings
│ └── services/
│ └── error.service.js # Error handling utilities
├── server.js # Entry point
├── package.json
└── README.md
- src/: Contains the core source code of the application.
- src/monitor.js: The main supervisor script that configures and runs
forever-monitor. - src/server.js: The HTTP server implementation that includes the intentional exit logic.
- src/settings/: Contains configuration files for environment and server settings.
- src/services/: Helper services, including error formatting and handling.
- .github/: GitHub-specific configuration, including repository rulesets.
- .vscode/: Workspace-specific settings for Visual Studio Code.
- Run
npm start - Observe server starting, exiting, and restarting
- Restart counter increments with each restart
- Change
max: 3insrc/monitor.js - Run
npm start - Monitor stops after 3 restarts
- Change
process.exit(2)toprocess.exit(1)insrc/server.js - Run
npm start - Monitor does NOT restart the server
- Change
SERVER_PORTinsrc/settings/settings.js - Run
npm start - Server starts on the new port
The project uses:
- JavaScript (Node.js) with ES6+ features
- forever-monitor for process management
- death for graceful process termination
- ESLint for code quality
This pattern is useful for:
- Production servers: Automatic recovery from crashes
- Long-running processes: Keep services alive
- Graceful Shutdown: Always use the
deathpackage or similar to handle process termination signals. - Limit Restarts: Set a reasonable
maxrestart limit to prevent infinite loops in case of unrecoverable errors. - Exit Codes: Use meaningful exit codes to differentiate between various types of failures.
- Logging: Ensure all process events (starts, restarts, exits) are logged for easier troubleshooting.
If you encounter any issues or have questions about this project:
- Issues: Report bugs or request features via GitHub Issues.
- Author: Or Assayag (orassayag@gmail.com)
- GitHub: @orassayag
- Development testing: Test restart/recovery logic
- Microservices: Ensure service availability
- Background jobs: Auto-restart failed workers
If port 3001 is in use:
- Change
SERVER_PORTin settings - Or stop the conflicting process
- On Windows:
npm run stop
- Press
Ctrl+Cto stop - On Windows:
npm run stop - Check
silent: falsefor visibility
- Set
silent: falseinsrc/monitor.js - Run with
npm startnotnode server.js
Contributions to this project are released to the public under the project's open source license.
Everyone is welcome to contribute. Contributing doesn't just mean submitting pull requests—there are many different ways to get involved, including answering questions and reporting issues.
Please feel free to contact me with any question, comment, pull-request, issue, or any other thing you have in mind.
- Or Assayag - Initial work - orassayag
- Or Assayag orassayag@gmail.com
- GitHub: https://github.com/orassayag
- StackOverflow: https://stackoverflow.com/users/4442606/or-assayag?tab=profile
- LinkedIn: https://linkedin.com/in/orassayag
This application has an MIT license - see the LICENSE file for details.
- Built for educational and research purposes
- Respects robots.txt and implements rate limiting
- Uses user-agent rotation to avoid detection
- Implements polite crawling practices