A large number of developers use Nodemon during the development and testing of Node.js apps. When your code file changes, Nodemon will automatically restart the program. However, when the app crashes, it will stop:
nodemon app crashed - waiting for file changes before starting
This is a deliberate behavior that intends to help you have time to read error messages and figure out what is going on. If Nodemon restarts your Node.js app on its own in this situation, chances are you’ll go into an endless loop of errors and your console will be flooded with duplicate messages. If you are aware of this and surely want Nodemon to automatically restart your Node.js program on a crash, then there is a simple solution for you.
For Mac and Linux, use the following command:
nodemon -x 'node index.js || touch index.js'
If you’re working with a Windows laptop, use this one:
nodemon -x 'node index.js || copy /b index.js +,,'
if your entry file is not named index.js but app.js, server.js, or anything else then change the command accordingly.
If you’ve worked with Node.js for a while then you’re very likely to know about pm2, a popular process manager for Node.js in production. However, pm2 can still be used for development purposes and it performs very well.
npm i --g pm2
sudo npm i --g pm2
Then you can run your app and watch for file changes like so:
pm2 start index.js --watch
- Node.js: Turn a Relative Path into an Absolute Path
- Node.js: How to Compress a File using Gzip format
- Node.js: Using __dirname and __filename with ES Modules
- Node.js: Reading and Parsing Excel (XLSX) Files
- 7 best Node.js frameworks to build backend APIs
You can also check out our Node.js category page for the latest tutorials and examples.