Tutorial

How To Restart Your Node.js Apps Automatically with Nodemon

Updated on October 15, 2024
authorauthor

Alligator.io and Bradley Kouchi

English
How To Restart Your Node.js Apps Automatically with Nodemon

Introduction

In Node.js, you need to restart the process to make changes take effect. This adds an extra step to your workflow. You can eliminate this extra step by using nodemon to restart the process automatically.

nodemon is a command-line interface (CLI) utility developed by rem that wraps your Node app, watches the file system, and automatically restarts the process.

In this article, you will learn about installing, setting up, and configuring nodemon.

Deploy your frontend applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.

How to Use Nodemon to Restart Node.js Apps Automatically

  1. Install Nodemon
  2. Set up example Express project with Nodemon
  3. Use options to modify configurations
  4. Use configurations in nodemon.json

Prerequisites

If you would like to follow along with this article, you will need:

This tutorial was verified with Node.js v17.1.0, npm v8.1.2, nodemon v2.0.15, and express v4.17.1.

These steps are valid for the most recent versions of Ubuntu: Ubuntu 24.04, Ubuntu 22.04, and Ubuntu 20.04. If you are using Ubuntu version <= 18.04, we recommend you upgrade to a more latest version since Ubuntu no longer provides support for the older versions. This collection of guides will help you in upgrading your Ubuntu version.

Step 1 — Installing Nodemon

First, you will need to install nodemon on your machine. Install the utility either globally or locally on your project using npm or yarn.

Global Nodemon Installation

You can install nodemon globally with npm:

npm install nodemon --global

Or with yarn:

yarn global add nodemon

Local Nodemon Installation

You can also install nodemon locally. When performing a local installation, you can install nodemon as a dev dependency with --save-dev (or --dev).

Install nodemon locally with npm:

npm install nodemon --save-dev

Or with yarn:

yarn add nodemon --dev

One thing to be aware of with a local install is that you will not be able to use the nodemon command directly:

Output
command not found: nodemon

You can execute the locally installed package:

./node_modules/.bin/nodemon.js [your node app]

You can also use it in npm scripts or with npx.

Step 2 — Setting Up an Example Express Project with Nodemon

You can use nodemon to start a Node script. For example, if you have an Express server setup in a server.js file, you can start nodemon and watch for changes like this:

nodemon server.js

You can pass in arguments the same way as if you were running the script with Node:

nodemon server.js 3006

Every time you make a change to a file with one of the default watched extensions (.js, .mjs, .json, .coffee, or .litcoffee) in the current directory or a subdirectory, the process will restart.

Let’s write an example server.js file that outputs the message: Dolphin app listening on port ${port}!.

server.js
const express = require('express')
const app = express()
const port = 3000

app.listen(port, ()=> console.log(`Dolphin app listening on port ${port}!`))

Run the example with nodemon:

nodemon server.js

The terminal output will display the following output:

Output
[nodemon] 2.0.15 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] starting `node server.js` Dolphin app listening on port 3000!

While nodemon is still running, let’s make a change to the server.js file. Change the output to a different message: Shark app listening on port ${port}!.

The terminal output will display the following output:

Output
[nodemon] restarting due to changes... [nodemon] starting `node server.js` Shark app listening on port 3000!

The terminal output from the Node.js app is displaying the new changes.

You can restart the process at any time by typing rs and hitting ENTER.

Alternatively, nodemon will also look for a main file specified in your project’s package.json file:

package.json
{
  // ...
  "main": "server.js",
  // ...
}

If a main file is not specified, nodemon will search for a start script:

package.json
{
  // ...
  "scripts": {
    "start": "node server.js"
  },
  // ...
}

Once you make the changes to package.json, you can then call nodemon to start the example app in watch mode without having to pass in server.js.

Step 3 — nodemon Options

You can modify the configuration settings available to nodemon.

Let’s go over some of the main options:

  • --exec: Use the --exec switch to specify a binary to execute the file with. For example, when combined with the ts-node binary, --exec can become useful to watch for changes and run TypeScript files.
  • --ext: Specify different file extensions to watch. For this switch, provide a comma-separated list of file extensions (e.g., --ext js,ts).
  • --delay: By default, nodemon waits for one second to restart the process when a file changes, but with the --delay switch, you can specify a different delay. For example, nodemon --delay 3.2 for a 3.2-second delay.
  • --watch: Use the --watch switch to specify multiple directories or files to watch. Add one --watch switch for each directory you want to watch. By default, the current directory and its subdirectories are watched, so with --watch you can narrow that to only specific subdirectories or files.
  • --ignore: Use the --ignore switch to ignore certain files, file patterns, or directories.
  • --verbose: A more verbose output with information about what file(s) changed to trigger a restart.

You can view all the available options with the following command:

nodemon --help

Using these options, let’s create the command to satisfy the following scenario:

  • watching the server directory
  • specifying files with a .ts extension
  • ignoring files with a .test.ts suffix
  • executing the file (server/server.ts) with ts-node
  • waiting for three seconds to restart after a file changes
nodemon --watch server --ext ts --exec ts-node --ignore '*.test.ts' --delay 3 server/server.ts

The terminal output will display the following output:

Output
[nodemon] 2.0.15 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): server [nodemon] watching extensions: ts [nodemon] starting `ts-node server/server.ts`

This command combines --watch, --ext, --exec, --ignore, and --delay options to satisfy the conditions for our scenario.

Step 4 — nodemon Configurations

In the previous example, adding configuration switches when running nodemon can get tedious. A better solution for projects that require complicated configurations is to define these options in a nodemon.json file.

For example, here are the same configurations as the previous command line example, but placed in a nodemon.json file:

nodemon.json
{
  "watch": [
    "server"
  ],
  "ext": "ts",
  "ignore": [
    "*.test.ts"
  ],
  "delay": "3",
  "execMap": {
    "ts": "ts-node"
  }
}

Note the use of execMap instead of the --exec switch. execMap allows you to specify binaries for certain file extensions.

Alternatively, if you would rather not add a nodemon.json config file to your project, you can add these configurations to the package.json file under a nodemonConfig key:

package.json
{
  "name": "nodemon-example",
  "version": "1.0.0",
  "description": "",
  "nodemonConfig": {
    "watch": [
      "server"
    ],
    "ext": "ts",
    "ignore": [
      "*.test.ts"
    ],
    "delay": "3",
    "execMap": {
      "ts": "ts-node"
    }
  },
  // ...

Once you make the changes to either nodemon.json or package.json, you can then start nodemon with the desired script:

nodemon server/server.ts

nodemon will pick up the configurations and use them. This way, your configurations can be saved, shared, and repeated to avoid copy-and-pasting or typing errors in the command line.

Conclusion

In this article, you explored how to use nodemon with your Node.js applications. This tool helps automate the process of stopping and starting a Node server to view the changes.

For more information about the available features and troubleshooting errors, consult the official nodemon documentation.

If you’d like to learn more about Node.js, check out our Node.js topic page for exercises and programming projects.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Alligator.io

author



Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
2 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

praise to nodemon but maybe try alternativ https://github.com/jbystronski/watcher

nodemonConfig key in package.json and nodemon.json both take parameters for “delay” key in milliseconds rather than seconds.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.