Sometimes we encounter the need to run a Node project, and in case it fails for any reason, we want to run it again. While nodemon is a great tool for automatically restarting a Node process when a file changes, it does not have built-in functionality to handle process crashes. However, we can find a workaround for this issue.

One solution I found is to use the touch command in the command line to trigger a file change detection by nodemon, even if no actual file changes have occurred. Here’s how it works:

nodemon -x 'node app.js || touch app.js'

With this command, if the app.js process crashes, the touch command will be executed, indicating a change in the file to nodemon. As a result, nodemon will automatically restart the process.

Keep in mind that while this solution is suitable for running the project on a local machine for a few hours, in a production environment, it’s recommended to use more robust solutions like pm2. If you are interested in learning how to use pm2 to serve a Node.js app, check out my tutorial how to use pm2 to serve a Node.js app.

Update: An alternative to nodemon is using Forever. You can find more information about Forever here.

Tags: nodemon, node.js, process restart, file changes, pm2, Forever