Node.js Watch Mode: How to Auto-Restart with –watch

This article explains how to use the built-in --watch command-line flag in Node.js to automatically restart your application whenever file changes are detected. You will learn the basic CLI syntax, how to target specific directories, and how to integrate this flag into your package.json scripts to create a native, dependency-free development environment.

The Basic Command

Historically, Node.js developers relied on third-party tools like nodemon to restart processes during development. Starting with Node.js v18.11.0, a native watch mode is built directly into the runtime.

To start your application in watch mode, prepend the --watch flag to your execution command in your terminal:

node --watch index.js

When you run this command, Node.js monitors the entry file (index.js) and any imported modules. If you modify and save any of these files, the process terminates and restarts automatically.

Watching Specific Paths

By default, the --watch flag monitors the entry point and its dependency tree. If you want to watch specific directories or files that are not directly imported (such as configuration files or assets), you can use the --watch-path flag.

node --watch --watch-path=./src --watch-path=./config index.js

You can specify the --watch-path flag multiple times to monitor different directories.

Configuring package.json for Ease of Use

To avoid typing the CLI flags every time, you can configure the watch command inside your project’s package.json file under the scripts object.

Open your package.json and add a development script:

{
  "name": "my-node-app",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "dev": "node --watch index.js"
  }
}

Now, you can start your development server with auto-restart enabled by running:

npm run dev