From 204647b558b6f7c67b37961c496640645396b1ba Mon Sep 17 00:00:00 2001 From: harshilv17 Date: Tue, 10 Nov 2026 11:32:11 +0530 Subject: [PATCH 1/2] feat: add --on-watch option to run a command on watched changes Closes #569 Signed-off-by: harshilv17 --- README.md | 1 + args.js | 2 ++ help/start.txt | 5 +++ lib/watch/index.js | 38 ++++++++++++++++++----- start.js | 2 +- test/args.test.js | 9 ++++++ test/watch-unit.test.js | 67 ++++++++++++++++++++++++++++++++++++++++- 7 files changed, 115 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index a18971cd..b1543ea0 100644 --- a/README.md +++ b/README.md @@ -167,6 +167,7 @@ You can pass the following options via CLI arguments. You can also use `--config | Ignore changes to the specified files or directories when watch is enabled. (e.g. `--ignore-watch='node_modules .git logs/error.log'` ) | | `--ignore-watch` | `FASTIFY_IGNORE_WATCH` | | Watch changes only into the specified files or directories when watch is enabled. (e.g. `--follow-watch='plugins/'` ) | | `--follow-watch` | `FASTIFY_FOLLOW_WATCH` | | Prints events triggered by watch listener (useful to debug unexpected reload when using `--watch` ) | `-V` | `--verbose-watch` | `FASTIFY_VERBOSE_WATCH` | +| Run a shell command on every watched change, before the process reloads (e.g. `--on-watch='npm run lint'` ). Add files the command writes to `--ignore-watch` | | `--on-watch` | `FASTIFY_ON_WATCH` | | Use custom options | `-o` | `--options` | `FASTIFY_OPTIONS` | | Set the prefix | `-x` | `--prefix` | `FASTIFY_PREFIX` | | Set the plugin timeout | `-T` | `--plugin-timeout` | `FASTIFY_PLUGIN_TIMEOUT` | diff --git a/args.js b/args.js index 452d603a..30f93c65 100644 --- a/args.js +++ b/args.js @@ -42,6 +42,7 @@ const CLI_OPTIONS = { method: { type: 'string' }, 'trust-proxy-ips': { type: 'string' }, 'follow-watch': { type: 'string' }, + 'on-watch': { type: 'string' }, 'pretty-logs': { type: 'boolean', short: 'P' }, options: { type: 'boolean', short: 'o' }, watch: { type: 'boolean', short: 'w' }, @@ -116,6 +117,7 @@ module.exports = function parseCliArgs (args) { commonPrefix: parsedArgs.commonPrefix, includeHooks: parsedArgs.includeHooks, followWatch: followWatchArg, + onWatch: parsedArgs.onWatch, trustProxy } } diff --git a/help/start.txt b/help/start.txt index 330da629..62dc158a 100644 --- a/help/start.txt +++ b/help/start.txt @@ -54,6 +54,11 @@ OPTS [env: FASTIFY_VERBOSE_WATCH] Print all watch events to the console + --on-watch + [env: FASTIFY_ON_WATCH] + Run a shell command on every watched change, before the process reloads (e.g. --on-watch='npm run lint'). + Add files the command writes to --ignore-watch, otherwise each run triggers the next one. + -x, --prefix [env: FASTIFY_PREFIX] Set the prefix diff --git a/lib/watch/index.js b/lib/watch/index.js index db58786f..73cf9a60 100644 --- a/lib/watch/index.js +++ b/lib/watch/index.js @@ -11,7 +11,7 @@ const chokidar = require('chokidar') const { loadEnvQuitely } = require('../../env-loader.js') const forkPath = path.join(__dirname, './fork.js') -const watch = function (args, ignoreWatch, verboseWatch, followWatch) { +const watch = function (args, ignoreWatch, verboseWatch, followWatch, onWatch) { const emitter = new EventEmitter() let allStop = false let childs = [] @@ -81,18 +81,42 @@ const watch = function (args, ignoreWatch, verboseWatch, followWatch) { const ignoredPattern = arrayToRegExp(ignoredArr) const watchDir = followWatch || process.cwd() const watcher = chokidar.watch(watchDir, { ignored: ignoredPattern }) + const restart = () => { + try { + const child = childs.shift() + child.send(GRACEFUL_SHUT) + } catch (err) { + // the previous child already exited: start a new one + childs.push(run('restart')) + } + } + // Changes made while the on-watch command runs are picked up by the restart + // that follows it, so they don't start another run. This also keeps a command + // that writes into the watched directory from triggering itself. + let onWatchRunning = false watcher.on('ready', function () { watcher.on('all', function (event, filepath) { if (verboseWatch) { logWatchVerbose(event, filepath) } - try { - const child = childs.shift() - child.send(GRACEFUL_SHUT) - } catch (err) { - // the previous child already exited: start a new one - childs.push(run('restart')) + if (!onWatch) { + return restart() + } + if (onWatchRunning) { + return } + onWatchRunning = true + cp.spawn(onWatch, { shell: true, stdio: 'inherit' }) + .on('error', (err) => console.log(chalk.red(err))) + .on('close', (code) => { + onWatchRunning = false + if (code !== 0) { + console.log(chalk.red(`[fastify-cli] on-watch command exited with code ${code}`)) + } + if (!allStop) { + restart() + } + }) }) }) diff --git a/start.js b/start.js index 28442fbb..566ad992 100755 --- a/start.js +++ b/start.js @@ -53,7 +53,7 @@ async function start (args) { loadModules(opts) if (opts.watch) { - return watch(args, opts.ignoreWatch, opts.verboseWatch, opts.followWatch) + return watch(args, opts.ignoreWatch, opts.verboseWatch, opts.followWatch, opts.onWatch) } return runFastify(args) diff --git a/test/args.test.js b/test/args.test.js index ef73b07f..f7085ad3 100644 --- a/test/args.test.js +++ b/test/args.test.js @@ -18,6 +18,7 @@ test('should parse args correctly', t => { '--ignore-watch', 'ignoreme.js', '--follow-watch', 'watchme.js', '--verbose-watch', 'true', + '--on-watch', 'npm run lint', '--options', 'true', '--prefix', 'FASTIFY_', '--plugin-timeout', '500', @@ -41,6 +42,7 @@ test('should parse args correctly', t => { watch: true, ignoreWatch: 'node_modules build dist .git bower_components logs .swp .nyc_output ignoreme.js', followWatch: 'watchme.js', + onWatch: 'npm run lint', verboseWatch: true, port: 7777, address: 'fastify.dev:9999', @@ -103,6 +105,7 @@ test('should parse args with = assignment correctly', t => { watch: true, ignoreWatch: 'node_modules build dist .git bower_components logs .swp .nyc_output ignoreme.js', followWatch: 'watchme.js', + onWatch: undefined, verboseWatch: true, port: 7777, address: 'fastify.dev:9999', @@ -186,6 +189,7 @@ test('should parse env vars correctly', t => { watch: true, ignoreWatch: 'node_modules build dist .git bower_components logs .swp .nyc_output ignoreme.js', followWatch: 'plugin/', + onWatch: undefined, verboseWatch: true, address: 'fastify.dev:9999', bodyLimit: 5242880, @@ -291,6 +295,7 @@ test('should parse custom plugin options', t => { watch: true, ignoreWatch: 'node_modules build dist .git bower_components logs .swp .nyc_output ignoreme.js', followWatch: 'watchme.js', + onWatch: undefined, verboseWatch: true, port: 7777, address: 'fastify.dev:9999', @@ -346,6 +351,7 @@ test('should parse config file correctly and prefer config values over default o debugHost: '1.1.1.1', ignoreWatch: 'node_modules build dist .git bower_components logs .swp .nyc_output', followWatch: '', + onWatch: undefined, verboseWatch: false, logLevel: 'fatal', address: 'fastify.dev:9999', @@ -392,6 +398,7 @@ test('should prefer command line args over config file options', t => { debugHost: '1.1.1.1', ignoreWatch: 'node_modules build dist .git bower_components logs .swp .nyc_output', followWatch: '', + onWatch: undefined, verboseWatch: false, logLevel: 'fatal', address: 'fastify.dev:9999', @@ -440,6 +447,7 @@ test('should favor trust proxy enabled over trust proxy ips and trust proxy hop' debugHost: '1.1.1.1', ignoreWatch: 'node_modules build dist .git bower_components logs .swp .nyc_output', followWatch: '', + onWatch: undefined, verboseWatch: false, logLevel: 'fatal', address: undefined, @@ -487,6 +495,7 @@ test('should favor trust proxy ips over trust proxy hop', t => { debugHost: '1.1.1.1', ignoreWatch: 'node_modules build dist .git bower_components logs .swp .nyc_output', followWatch: '', + onWatch: undefined, verboseWatch: false, logLevel: 'fatal', address: undefined, diff --git a/test/watch-unit.test.js b/test/watch-unit.test.js index 31d65545..b2ae69cb 100644 --- a/test/watch-unit.test.js +++ b/test/watch-unit.test.js @@ -10,7 +10,13 @@ const { GRACEFUL_SHUT } = require('../lib/watch/constants') // so the restart logic can be driven synchronously. function setup (t) { const forks = [] + const spawns = [] const childProcessMock = { + spawn (command, options) { + const proc = new EventEmitter() + spawns.push({ command, options, proc }) + return proc + }, fork () { const child = new EventEmitter() child.kill = t.mock.fn() @@ -35,7 +41,7 @@ function setup (t) { 'node:child_process': childProcessMock }) - return { watch, forks, watcher, uncaught } + return { watch, forks, spawns, watcher, uncaught } } test('should restart the child when a watched file changes', t => { @@ -120,6 +126,65 @@ test('should restart the child on an uncaught exception', t => { t.assert.strictEqual(forks.length, 2) }) +test('should run the on-watch command before restarting the child', t => { + const { watch, forks, spawns, watcher } = setup(t) + watch(['app.js'], 'node_modules', false, undefined, 'npm run lint') + + watcher.emit('ready') + watcher.emit('all', 'change', 'app.js') + + t.assert.strictEqual(spawns.length, 1) + t.assert.strictEqual(spawns[0].command, 'npm run lint') + t.assert.deepStrictEqual(spawns[0].options, { shell: true, stdio: 'inherit' }) + t.assert.strictEqual(forks[0].send.mock.callCount(), 0, 'no restart while the command runs') + + spawns[0].proc.emit('close', 0) + t.assert.strictEqual(forks[0].send.mock.calls[0].arguments[0], GRACEFUL_SHUT) + t.assert.strictEqual(console.log.mock.callCount(), 0) +}) + +test('should not start another on-watch run for changes made while one is running', t => { + const { watch, forks, spawns, watcher } = setup(t) + watch(['app.js'], 'node_modules', false, undefined, 'npm run lint') + + watcher.emit('ready') + watcher.emit('all', 'change', 'app.js') + watcher.emit('all', 'change', 'lib/a.js') + t.assert.strictEqual(spawns.length, 1) + + spawns[0].proc.emit('close', 0) + t.assert.strictEqual(forks[0].send.mock.callCount(), 1) + + watcher.emit('all', 'change', 'app.js') + t.assert.strictEqual(spawns.length, 2, 'a later change runs the command again') +}) + +test('should log a failing on-watch command and still restart the child', t => { + const { watch, forks, spawns, watcher } = setup(t) + watch(['app.js'], 'node_modules', false, undefined, 'npm run lint') + + watcher.emit('ready') + watcher.emit('all', 'change', 'app.js') + spawns[0].proc.emit('error', new Error('spawn failed')) + spawns[0].proc.emit('close', 1) + + t.assert.match(console.log.mock.calls[0].arguments[0], /spawn failed/) + t.assert.match(console.log.mock.calls[1].arguments[0], /on-watch command exited with code 1/) + t.assert.strictEqual(forks[0].send.mock.calls[0].arguments[0], GRACEFUL_SHUT) +}) + +test('should not restart after stop when the on-watch command finishes', t => { + const { watch, forks, spawns, watcher } = setup(t) + const emitter = watch(['app.js'], 'node_modules', false, undefined, 'npm run lint') + + watcher.emit('ready') + watcher.emit('all', 'change', 'app.js') + emitter.stop() + spawns[0].proc.emit('close', 0) + + t.assert.strictEqual(forks.length, 1) +}) + test('logWatchVerbose should print the relative path', t => { t.mock.method(console, 'log', () => {}) logWatchVerbose('add', `${process.cwd()}/lib/a.js`) From 18d65439dba167c4f880db0102fa45fd1a2f02d1 Mon Sep 17 00:00:00 2001 From: harshilv17 Date: Tue, 10 Nov 2026 12:06:57 +0530 Subject: [PATCH 2/2] fix: kill a running --on-watch command when the watcher stops Signed-off-by: harshilv17 --- lib/watch/index.js | 19 +++++++++++-------- test/watch-unit.test.js | 6 ++++-- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/lib/watch/index.js b/lib/watch/index.js index 73cf9a60..970baf1a 100644 --- a/lib/watch/index.js +++ b/lib/watch/index.js @@ -15,6 +15,8 @@ const watch = function (args, ignoreWatch, verboseWatch, followWatch, onWatch) { const emitter = new EventEmitter() let allStop = false let childs = [] + // The running on-watch command, if any + let onWatchProc = null const stop = (watcher = null, err = null) => { childs.forEach(function (child) { child.kill() @@ -26,6 +28,9 @@ const watch = function (args, ignoreWatch, verboseWatch, followWatch, onWatch) { } if (watcher) { allStop = true + if (onWatchProc) { + onWatchProc.kill() + } return watcher.close() } } @@ -90,10 +95,6 @@ const watch = function (args, ignoreWatch, verboseWatch, followWatch, onWatch) { childs.push(run('restart')) } } - // Changes made while the on-watch command runs are picked up by the restart - // that follows it, so they don't start another run. This also keeps a command - // that writes into the watched directory from triggering itself. - let onWatchRunning = false watcher.on('ready', function () { watcher.on('all', function (event, filepath) { if (verboseWatch) { @@ -102,14 +103,16 @@ const watch = function (args, ignoreWatch, verboseWatch, followWatch, onWatch) { if (!onWatch) { return restart() } - if (onWatchRunning) { + // Changes made while the command runs are picked up by the restart that + // follows it, so they don't start another run. + if (onWatchProc) { return } - onWatchRunning = true - cp.spawn(onWatch, { shell: true, stdio: 'inherit' }) + onWatchProc = cp.spawn(onWatch, { shell: true, stdio: 'inherit' }) + onWatchProc .on('error', (err) => console.log(chalk.red(err))) .on('close', (code) => { - onWatchRunning = false + onWatchProc = null if (code !== 0) { console.log(chalk.red(`[fastify-cli] on-watch command exited with code ${code}`)) } diff --git a/test/watch-unit.test.js b/test/watch-unit.test.js index b2ae69cb..8c7251ef 100644 --- a/test/watch-unit.test.js +++ b/test/watch-unit.test.js @@ -14,6 +14,7 @@ function setup (t) { const childProcessMock = { spawn (command, options) { const proc = new EventEmitter() + proc.kill = t.mock.fn() spawns.push({ command, options, proc }) return proc }, @@ -173,14 +174,15 @@ test('should log a failing on-watch command and still restart the child', t => { t.assert.strictEqual(forks[0].send.mock.calls[0].arguments[0], GRACEFUL_SHUT) }) -test('should not restart after stop when the on-watch command finishes', t => { +test('should kill a running on-watch command on stop and not restart', t => { const { watch, forks, spawns, watcher } = setup(t) const emitter = watch(['app.js'], 'node_modules', false, undefined, 'npm run lint') watcher.emit('ready') watcher.emit('all', 'change', 'app.js') emitter.stop() - spawns[0].proc.emit('close', 0) + t.assert.strictEqual(spawns[0].proc.kill.mock.callCount(), 1) + spawns[0].proc.emit('close', null) t.assert.strictEqual(forks.length, 1) })