0
0
NodejsHow-ToBeginner · 4 min read

How to Use Nodemon in Node.js for Automatic Server Restart

Use nodemon to automatically restart your Node.js app when files change by installing it with npm install -g nodemon and running your app with nodemon your-app.js. This saves time by avoiding manual restarts during development.
📐

Syntax

The basic syntax to run your Node.js app with nodemon is:

  • nodemon <script>: Starts nodemon to watch your script file and restart on changes.
  • nodemon --watch <folder>: Watches a specific folder for changes.
  • nodemon --ext <extensions>: Watches files with specific extensions.
bash
nodemon app.js
nodemon --watch src --ext js,json app.js
💻

Example

This example shows how to run a simple Node.js server with nodemon. When you save changes to server.js, nodemon restarts the server automatically.

javascript
const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello from nodemon!');
});

server.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000
⚠️

Common Pitfalls

Common mistakes when using nodemon include:

  • Not installing nodemon globally or locally before use.
  • Running node app.js instead of nodemon app.js, which disables auto-restart.
  • Not saving files after changes, so nodemon does not detect updates.
  • Ignoring configuration files like nodemon.json for complex setups.
bash
/* Wrong way - nodemon not used */
node server.js

/* Right way - use nodemon */
nodemon server.js
📊

Quick Reference

CommandDescription
nodemon app.jsStart app with nodemon watching all files
nodemon --watch src app.jsWatch only the src folder
nodemon --ext js,json app.jsWatch only .js and .json files
nodemon --delay 2 app.jsWait 2 seconds before restarting
nodemon --exec "npm run start" app.jsRun custom command on restart

Key Takeaways

Install nodemon globally with npm to use it anywhere.
Run your app with nodemon instead of node to auto-restart on changes.
Use --watch and --ext options to control which files nodemon watches.
Save your files to trigger nodemon restarts.
Use nodemon.json for advanced configuration.