NodeJS by Example: Watch Mode
|
Watch Mode automatically restarts your Node.js application when files change. It's built into Node.js - no external tools needed. |
|
|
Basic Watch Mode Run with: node --watch script.js Node.js will restart automatically when the file changes. |
|
|
What Gets Watched By default, Node.js watches: - The main script file - All imported/required modules Example server that demonstrates watch mode |
|
|
Watch Specific Paths Use --watch-path to watch additional directories node --watch --watch-path=./src --watch-path=./config script.js |
|
|
Preserving State Watch mode restarts the entire process, so state is lost. Use external storage (files, databases) to preserve state across restarts. To preserve: write to file or use a database |
|
|
Watch Mode vs nodemon Built-in watch mode advantages: - No dependencies needed - Faster startup - Works with latest Node.js features nodemon advantages: - More configuration options - Can run non-Node.js scripts - Supports ignore patterns |
|
|
Development Workflow Typical development setup in package.json: { "scripts": { "start": "node server.js", "dev": "node --watch server.js", "dev:debug": "node --watch --inspect server.js" } } |
|
|
Combining with Other Flags Watch mode works with other Node.js flags node --watch --inspect server.js # With debugger node --watch --env-file=.env server.js # With env file node --watch --experimental-strip-types server.ts # With TypeScript |
|
|
Watch Events The process receives events when files change |
|
|
Tips for Watch Mode 1. Keep startup time fast - watch mode restarts frequently 2. Use environment variables for configuration 3. Handle SIGTERM for graceful shutdown 4. Use --watch-path for monorepos with multiple packages |
|
|
Debugging with Watch Mode Combine --watch with --inspect for debugging node --watch --inspect server.js Then attach your debugger (VS Code, Chrome DevTools) |
|
|
Run in watch mode When you save the file: |
|
|
Watch specific paths |
|
|
Combine with debugging |
|