brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: node --watch restarts your script when a file changes

Tools
~/tips/tip-javascript-node-watch-restart

node --watch index.js

Starts a Node.js script in watch mode, so it restarts by itself each time you save a file it uses.

For a long time restarting a small server after every edit meant installing nodemon. Node.js has a built-in flag for it.

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

The Node.js documentation says that in watch mode, changes in the watched files cause the process to restart. By default it watches the entry point and every module that is required or imported from it. --watch-path lets you pick the paths yourself.

As for versions, the flag was added in v18.11.0 and v16.19.0, and watch mode became stable in v22.0.0 and v20.13.0. Run node --version to see where you are.

It suits small servers, scripts and tests. Edit a file, save, and the output of the new run appears in the same terminal.

The caveat is that it restarts the whole process. It is not hot module replacement, so anything in memory, such as sessions, caches and connections, starts from zero on each save. The documentation also says it cannot be combined with --check, --eval, --interactive or the REPL. And --watch-path is only supported on macOS and Windows according to the same page, so on Linux use plain --watch and let it follow the imports.

Further reading: Node.js documentation: command-line options (–watch)

More Tools tips shuf -n 3 films.txt xmllint --format feed.xml pdftotext -layout invoice.pdf invoice.txt qrencode -t ANSIUTF8 'https://example.com/a/long/path?id=12345' where python All Tools tips (14) All topics

Link