Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readNode

Restart a Node server with --watch

Run node --watch to restart a server when its entry file or any module it imports changes, and see how it handles a crash.

You installed nodemon in a project with one server file, and you use it for one job, restarting after you save. Node does that without a dependency.

Take a server that answers every request with a greeting it imports from another file.

// greeting.mjs
export const greeting = 'hello'

// server.mjs
import { createServer } from 'node:http'
import { greeting } from './greeting.mjs'

createServer((req, res) => {
  res.end(`${greeting}\n`)
}).listen(4173, () => console.log('listening on 4173'))

The server answers on port 4173 and prints a line when it is ready.

Run it with --watch

Start it with the --watch flag, which Node has marked stable since Node 20.13 and 22.

# terminal 1
$ node --watch server.mjs
listening on 4173
Restarting 'server.mjs'
listening on 4173

# terminal 2
$ curl localhost:4173
hello
# edit greeting.mjs so it exports 'hello again', then save
$ curl localhost:4173
hello again

Edit greeting.mjs and wait for the second listening line before running curl again. Node watches the entry file and the modules it loads through imports or requires by default.

Running touch server.mjs can force a restart. Add --watch-preserve-output if you want to keep earlier logs visible.

What a crash does

Add throw new Error('boom') to greeting.mjs and save. The process exits, and Node keeps the watcher alive.

Restarting 'server.mjs'
file:///.../greeting.mjs:2
throw new Error('boom')
      ^

Error: boom
Failed running 'server.mjs'. Waiting for file changes before restarting...

Remove the throw and save, and the output goes back to Restarting 'server.mjs' and listening on 4173. You do not run the command again after a bug. The error text and the "Waiting for file changes" line tell you the process is down and the watcher is still running.

Watch a folder instead

--watch-path takes the paths to watch. It turns off the default watching of imported modules and implies --watch.

Create a src folder next to server.mjs. I ran node --watch-path=./src server.mjs with greeting.mjs outside ./src. Editing greeting.mjs did not restart the server, and curl still printed hello. Writing a file inside ./src restarted it, and the new greeting appeared.

The Node docs say --watch-path is supported only on macOS and Windows. On other platforms Node throws ERR_FEATURE_UNAVAILABLE_ON_PLATFORM.