Restarting a Node process without file changes
By Flavio Copes
Learn how to make nodemon restart a Node process after a crash, not just on file changes, with a trick that runs touch on your app file when it exits.
To restart a Node process after a crash with nodemon, tell nodemon to touch the app file when the process exits with an error. The file change triggers the restart.
Here’s the story. I had to run a Node project for a few hours, and if it failed for some reason, run it again.
I had the idea of using nodemon, which is the tool we use to restart a Node process when a file changes.
I was thinking it did the same when the process crashed, but that’s not how it works. When the app crashes, nodemon prints app crashed - waiting for file changes before starting... and stops there. It waits for you to save a file.
Why doesn’t nodemon restart on a crash?
It makes sense during development. If the app crashes because of a bug, restarting it in a loop gets you nowhere. You fix the code, you save, nodemon restarts. That’s the workflow nodemon is built for.
My case was different. The process failed for external reasons, not because of a bug in the code, so restarting it was exactly what I wanted.
The trick
nodemon has a -x (or --exec) flag that replaces the command it runs. Instead of letting it run node app.js, we pass our own command:
nodemon -x 'node app.js || touch app.js'
nodemon runs node app.js. If the process exits with a non-zero code, the || operator runs touch app.js. That updates the file’s modification time, nodemon detects the “change”, and restarts the process.
If the process exits cleanly with code 0, || skips the touch and nothing restarts. Which is usually what you want: a clean exit means the work is done.
Note the quotes around the command. Without them, your shell interprets the || itself instead of passing the whole command to nodemon.
One thing to watch out for: if the app crashes right at startup, you get a very fast restart loop. Adding --delay 2 tells nodemon to wait 2 seconds after a change before restarting, which keeps the loop under control.
Of course in a real environment you’d use a robust solution like pm2 (see my tutorial how to use pm2 to serve a Node.js app) or a systemd service (I built a free systemd service generator for Node apps), but this is something I needed to run for a couple hours on my local machine, and it works.
Update: an alternative is using Forever https://www.npmjs.com/package/forever
Related posts about node: