How to restart a Node.js app with watch mode

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.

Steps to restart a Node.js app with watch mode:

  1. 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.

  2. 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');
    });
    EOF

    Use another local port if 3000 is already assigned to a different development service.

  3. 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.

  4. Request the app before changing the watched module.
    $ curl -sS http://127.0.0.1:3000/
    ready v1
  5. Replace the imported message module with a changed value.
    $ cat > message.mjs <<'EOF'
    export const message = 'ready v2';
    EOF
  6. 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.

  7. Request the app again after Node.js restarts it.
    $ curl -sS http://127.0.0.1:3000/
    ready v2
  8. Stop the watch-mode process with Ctrl-C.
  9. Remove the sample files when they are no longer needed.
    $ rm server.mjs message.mjs