Sling Academy
Home/Node.js/Nodemon: Only Re-Run the Code When a Specific File Changes

Nodemon: Only Re-Run the Code When a Specific File Changes

Last updated: December 30, 2023

Nodemon is a utility that monitors for any changes in your Node.js applications and automatically restarts the server. This tutorial teaches how to configure Nodemon to only re-run code when specific files change, optimizing development workflows.

Before getting started, ensure you have Node.js installed. Knowledge of the terminal and fundamental Node.js concepts is also recommended.

Using the –watch flag

Installing Nodemon:

npm install -g nodemon

Basic Nodemon usage:

nodemon app.js

Where app.js is your entry file.

Monitoring specific files:

nodemon --watch app.js

Nodemon will now only restart when app.js changes.

For debugging with Nodemon, use the --inspect flag:

nodemon --inspect app.js

Modifying nodemon.json

Creating a nodemon.json file:

{
  "watch": ["server.js"]
}

Using wildcards to watch all JavaScript files in a specific directory:

{
  "watch": ["src/**/*.js"]
}

Ignoring Files:

{
  "ignore": ["src/tests/*"]
}

Type rs and press enter in the terminal where nodemon is running to restart Nodemon manually.

Scripting with package.json

{
  "scripts": {
    "dev": "nodemon -e js,ts --watch src/app.ts"
  }
}

Now you can start your nodemon monitoring with npm run dev.

Conclusion

By specifying files, you can enhance your development workflow with Nodemon, ensuring only necessary code reloads. Tailor this versatile tool to your project’s needs for a more efficient coding experience.

Previous Article: Node.js vs Django: Which is better for backend development?

Series: The First Steps to Node.js

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates