Node.js Reference ยท CLI Flags
Node.js --watch and --watch-path flags
Reference for node --watch, --watch-path and --watch-preserve-output: restart a script when files change, choose which paths to watch, and know the limits.
node --watch app.js runs a script and restarts it whenever a file it depends on changes. It replaces most uses of nodemon during development: no extra package, and it knows the real module graph, so only files your program actually loads trigger a restart.
By default it watches the entry point and every file loaded through require() or import. With --watch-path you choose the paths yourself, which also lets you watch files that are read at runtime, such as templates or JSON configuration.
node --watch server.js node --watch-path=./src --watch-path=./config server.js
Try it
The first example starts a watcher, edits the script and shows the restart, then stops it. The restart takes a moment, so the example waits for the output rather than for a fixed time.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
node --watch script.js node --watch-path=<path> [--watch-path=<path> ...] script.js node --watch --watch-preserve-output script.js node --watch --test
| Flag | Description |
|---|---|
--watch |
Watch the entry point and every module it loads, and restart when one changes. |
--watch-path=path |
Watch this file or directory instead of the automatic set. Repeat the flag for several paths. |
--watch-preserve-output |
Do not clear the terminal at each restart. |
Behavior: when a change is seen, Node sends the process a termination signal, waits for it to exit, and starts it again with the same arguments. If the process crashes, the watcher stays up and waits for the next edit.
Usage notes
- Stable.
--watchwas experimental when it arrived in Node 18.11 and 16.19, and is stable in current LTS releases. - Not hot reload. Each change restarts the whole process, so in-memory state is lost. Keep development data in files or a database.
- Files read at runtime are not tracked by plain
--watch. A template read withfs.readFilein a request handler will not trigger a restart unless it is covered by--watch-path. - Combine with the test runner.
node --watch --testreruns the tests when sources or tests change. - Clean shutdown matters. The old process receives a termination signal; handle
SIGTERMto close servers and release ports, otherwise the restart may fail withEADDRINUSE. - Not for production. Restart on file change belongs in development; use a process manager or container orchestrator in production.
- Ignored directories. Watching
node_modulesis usually unnecessary; with--watch-pathlist only your own source folders to keep restarts quick.