Node.js watch mode keeps a local development process tied to the files it loads, so a source edit restarts the app without adding nodemon or another watcher package. It is useful when testing small services, scripts, or framework-free prototypes where the important signal is the process starting again after a changed module is saved.
The built-in --watch flag watches the entry point and imported modules by default. Adding --watch-preserve-output keeps previous console output visible across restarts, which makes the restart line and the next startup message easier to inspect while developing.
A minimal HTTP server and an imported message module provide a visible check. The first request returns one value, the saved module edit restarts Node.js, and the next request returns the changed value. Keep watch mode for local development; production restarts, crash recovery, and boot persistence belong to a process manager or service supervisor.
Related: How to create an HTTP server in Node.js
Related: How to manage a Node.js app with PM2
Steps to restart a Node.js app with watch mode:
- Create a message module for the app to import.
$ cat > message.mjs <<'EOF' export const message = 'ready v1'; EOF
The .mjs extension keeps the sample in ES modules mode without adding a /package.json file.
- Create a small HTTP server that uses the imported value.
$ cat > server.mjs <<'EOF' import http from 'node:http'; import { message } from './message.mjs'; const server = http.createServer((req, res) => { res.end(`${message}\n`); }); server.listen(3000, () => { console.log('server listening on http://127.0.0.1:3000'); }); EOFUse another local port if 3000 is already assigned to a different development service.
- Start the app with Node.js watch mode.
$ node --watch --watch-preserve-output server.mjs server listening on http://127.0.0.1:3000
Plain --watch works on Linux, macOS, and Windows. Use --watch-path only on macOS and Windows when explicit watched directories are needed.
- Request the app before changing the watched module.
$ curl -sS http://127.0.0.1:3000/ ready v1
- Replace the imported message module with a changed value.
$ cat > message.mjs <<'EOF' export const message = 'ready v2'; EOF
- Check the watch-mode terminal after saving the module.
server listening on http://127.0.0.1:3000 Restarting 'server.mjs' server listening on http://127.0.0.1:3000
The restart line appears in the terminal where node --watch is still running.
- Request the app again after Node.js restarts it.
$ curl -sS http://127.0.0.1:3000/ ready v2
- Stop the watch-mode process with Ctrl-C.
- Remove the sample files when they are no longer needed.
$ rm server.mjs message.mjs
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.