watch-util v1.0.5
Versatile watcher lib and shell commands for watching files, running and restarting shell commands
Watch files, run and restart shell commands on changes.
Provides both API and shell commands with consistent options naming.
var watch = require("watch-util");
// with callback
var globs = ["**/*", "!node_modules/", "!test/", "test/test.js"];
var options = { events: ["create", "change"], combineEvents: false };
var w = new watch.Watcher(globs, options, function (filePath, event) {
/* ... */
});
w.start();
// or listen to events
var w = new watch.Watcher(["**/*"]);
w.start();
w.on("create", function (filePath) { /* ... */ });
w.on("change", function (filePath) { /* ... */ });
w.on("delete", function (filePath) { /* ... */ });
w.on("all", function (filePath, event) { /* ... */ });
// or run cmd
var options = { waitDone: true, stdio: [null, "pipe", "pipe"] };
var w = watch.exec(["**/*.js"], options, "echo file %relFile is changed");
w.stdout.on("data", function (data) { /* ... */ });
w.stderr.on("data", function (data) { /* ... */ });
// or run server/daemon-like cmd
var options = { throttle: 1000, stdio: [null, "inherit", "inherit"] };
var w = watch.restart(["**/*", "!node_modules/"], options, "node server.js");watch-exec -g '**/*.js, !node_modules/' --debounce 5000 -- echo changed files: %relFiles
watch-exec -g '**/*.js, !node_modules/' -C -- echo event=%event relFile=%relFile
watch-restart -g '**/*.js,!node_modules/' --check-md5 -- node server.jsInstall:
npm install watch-utilAPI:
- watch.Watcher - watch files and execute callback when files are changed or listen to events
- watch.exec(globs, options, cmd) - execute cmd when files are changed
- watch.restart(globs, options, cmd) - run and restart cmd when files are changed
Shell commands:
- watch-exec - shell analog of
watch.exec - watch-restart - shell analog of
watch.restart
Features
- Watch by globs, negate globs, apply globs sequentially
- Compare MD5 of files
- Compare mtime of files
- Doesn't fire duplicate events
- Handle 2-step save that is used in most of the popular editors
- Execute cmd on changes
- Pass file path, event, etc. to cmd
- Execute cmd for each changed file in parallel
- Execute cmd in queue
- Restart cmd on changes
- Debounce change events
- Throttle cmd exec/restart
- Kill processes reliably
watch.Watcher #
new watch.Watcher(globs, options, callback)
new watch.Watcher(globs, callback)
new watch.Watcher(globs)
new watch.Watcher(globs, options)globs<Array>Glob patterns to watch, see Globs optionoptions<Object>debounce<integer>Callback and events will not fire until N ms will pass from the last event, default50throttle<integer>Call callback and fire events no more then once in N ms, default0reglob<integer>Interval to rerun glob to check for added directories and files, default1000events<Array>Call callback and fire events only for specified list of watch events, default["create", "change", "delete"]combineEvents<boolean>Combine all files changes during the debounce into single event, defaulttruecheckMD5<boolean>Check MD5 of files to prevent firing when content is not changed, defaultfalsecheckMtime<boolean>Check modified time of files, used for 2-step save, defaulttruedeleteCheckInterval<integer>Interval to check if file is replaced, default25deleteCheckTimeout<integer>Delay to determine if file is replaced or deleted, default100debugPrint debug information, defaultfalsecallback<Function>
Watch files by glob. Could be used without callback.
Doesn't start in constructor. Call watcher.start() to start watching files.
Note! Don't forget to call watcher.stop() in process.on("exit") or process.on(signal) to kill all running processes before exiting.
globs option #
To ignore specific pattern prefix it with '!'. To ignore directory with everything within it end pattern with '/' or '/**'.
Patterns are applied sequentially to allow for globs like:
["**/*.js", "!test/", "test/test.js"]For more info about glob syntax see: glob.
watcher.start(callback)
Start watching files. Callback is called after mathing files with glob and creating watchers.
Note! Changes may not be recognized rignt after the .start callback, fs.watch watchers start watching files with small delay.
watcher.stop(callback)
Stop all watchers and clear all timers.
watcher.stdout
Pass-through for running cmd stdout.
When options .stdio[1] is set to 'pipe' creates pass-through stream for the running commands. Stream doesn't end when cmd process exits.
watcher.stderr
Pass-through for running cmd stderr.
When options .stdio[2] is set to 'pipe' creates pass-through stream for the running commands. Stream doesn't end when cmd process exits.
Events: "create", "change", "delete"
file|files<string>|<Array>Relative path/paths of changed files
Is emitted when file/files are created, changed or deleted.
Is not emitted when option .combineEvents == true
Event: "all"
file|files<string>|<Array>Relative paths/paths of changed filesevent"create", "change" or "delete"
Is emitted when file/files are created, changed or deleted.
Event: "error"
err
Is emitted when fs operations fail, most of the fails will not prevent watcher from working.
Note! Add handler to this event or it will be thrown instead.
Event: "start"
Is called after .start() is finished.
Event: "stop"
Is called after .stop() is finished.
watch.exec(globs, options, cmd) #
Run cmd every time files are changed. Creates watchers immediately.
watch.exec(globs, options, cmd)
watch.exec(globs, cmd)globs<Array>Glob patterns to watch, see Globs optionoptions<Object>Allnew watch.WatcheroptionswaitDone<boolean>Wait untilcmdexit until executing again, defaulttrueparallelLimit<boolean>Number of parallel runningcmds when.combineEvents == false, default8restartOnError<boolean>Restartcmdif it crashed or exited with non0code, defaultfalseshell<boolean>|<string>Use default shell to runcmd, when is string specifies custom shell, defaulttruestdio<array, default[null, "ignore", "ignore"]*kill<Object>Options forkill(), see kill-with-stylecmd<string>Command to run on changes- Returns
<watch.Watcher>with additional events
When option .waitDone == true all changes will be placed into queue, if .combineEvents == false uses separate queues per file.
Changes in queue are optimized, that way if there are multiple changes for the file between runs, cmd will be executed only once.
When options .waitDone == false current running cmd will be killed and run again, if .combineEvents == false kills/runs only cmd that is processing the same file that is changed.
When .stop() is called all running processes will be killed. Calllback is called after all processes are killed.
Note! Don't forget to call watcher.stop() in process.on("exit") or process.on(signal) to kill all running processes before exiting.
cmd could contain variables that will be replaced with changed file names, events, etc.
cmd interpolation variables:
%relFilesRelative changed files paths%filesAbsolute changed files paths%cwdDir to resolve relative paths
cmd interpolation variables with -C, --no-combine-events:
%relFileRelative changed file path%fileAbsolute changed file path%relDirRelative dir containing changed file%dirAbsolute dir containing changed file%cwdDir to resolve relative paths%eventFile event: create, change or delete
Event: "exec"
cmd<string>Interpolated command
Is fired when cmd is run.
Event: "exit"
cmd<string>Interpolated command
Is fired when cmd is exited with any code.
Event: "crash"
cmd<string>Interpolated command
Is fired when cmd is exited with code other then 0.
Event: "kill"
cmd<string>Interpolated command
Is fired when cmd is killed.
watch.restart(globs, options, cmd) #
watch.restart(globs, options, cmd)
watch.restart(globs, cmd)Run cmd and restart every time files are changed. Creates watchers and runs cmd immediately.
globs<Array>Glob patterns to watch, see Globs optionoptions<Object>Allnew watch.WatcheroptionsrestartOnError<boolean>Restartcmdif it crashed or exited with non0code, defaulttruerestartOnSuccess<boolean>Restartcmdis it exited with0code, defaulttrueshell<boolean>|<string>Use default shell to runcmd, when is string specifies custom shell, defaulttruestdio<array, Parameters for child stdio infs.spawn, default[null, "ignore", "ignore"]kill<Object>Options forkill(), see kill-with-stylecmd<string>Command to run and restart on changes- Returns
<watch.Watcher>with additional events
When .stop() is called all running processes will be killed. Calllback is called after all processes are killed.
Note! Don't forget to call watcher.stop() in process.on("exit") or process.on(signal) to kill all running processes before exiting.
Event: "exec"
cmd<string>
Is fired when cmd is run.
Event: "exit"
cmd<string>
Is fired when cmd is exited with any code.
Event: "crash"
cmd<string>
Is fired when cmd is exited with code other then 0.
Event: "kill"
cmd<string>
Is fired when cmd is killed.
Event: "restart"
cmd<string>
Is fired when cmd is restarted.
watch-exec #
Run <shell cmd> every time files are changed.
If -C, --no-combine-events cmd will be executed for each file in parallel, debounce and throttle will be used per file.
Usage:
watch-exec --glob <globs> [options] -- <shell cmd>Examples:
watch-exec -g '*.js,test/*' -- './node_modules/.bin/mocha --colors test/test.js'
watch-exec -g '**/*.js, !node_modules/' --debounce 5000 -- echo changed files: %relFiles
watch-exec -g '**/*.js, !node_modules/' -C -- echo event=%event relFile=%relFileOptions:
-g, --globs <patterns>Glob patterns to watch, separated by comma, to ignore pattern start it with '!'--events <events>Exec only for specified events, separated by comma, possible values: create, change, delete-d, --debounce <ms>Exec cmd only after no events for N ms, default50-t, --throttle <ms>Exec cmd no more then once in N ms, default0-C, --no-combine-eventsDon't combine all events during debounce into single call--run-on-start"Run after starting the command, before any change events--reglob <ms>Glob files every N ms to track added files/dirs, default1000--check-md5Check md5 checksum of files and fire events only if checksum is changed--no-check-mtimeDon't check mtime of files and fire events only if mtime is changed--parallel-limit <n>Max number of parallel running cmds-w, --wait-doneDon't kill cmd on event, queue another run after it's done--restart-on-errorRestart cmd if cmd crashed or exited with non 0 code--shell <shell cmd>Custom shell to use for running cmd--no-shellRun directly without shell--kill-signal <signals>Signal to send to child when process.kill(pid, signal), separated by comma--kill-timeout <ms>After which return with error--kill-retry-interval <intervals>Intervals between sending of kill signal, separated by comma--kill-retry-count <n>Number of retries--kill-check-interval <ms>Interval between checks if process is dead--kill-use-pgidUse PGID to get all children on mac/linux--kill-children-immediatelyKill children immediately, don't wait for parent to die--silentNo output from watcher and running cmd-v, --verboseLog when files are changed and cmd is executed-V, --versionOutput version
watch-restart #
Run <shell cmd> and restart every time files are changed.
Usage:
watch-restart --glob <globs> [options] -- <shell cmd>Examples:
watch-restart -g '**/*.js,!node_modules/' node server.js");
watch-restart -g '**/*.js,!node_modules/' --debounce 500 --throttle 2000 node server.js
watch-restart -g '**/*.js,!node_modules/' --check-md5 --kill-signal 'SIGTERM,SIGTERM,SIGKILL' --kill-retry-interval '100,200,500' -- node server.js
watch-restart -g '**/*.js,!node_modules/' --shell node 'console.log(\"run\"); setInterval(()=>{}, 1000)'Options:
-g, --globs <patterns>Glob patterns to watch, separated by comma, to ignore pattern start it with '!'--events <events>Restart only for specified events, separated by comma, possible values: create, change, delete-d, --debounce <ms>Restart cmd only after no events for N ms, default50-t, --throttle <ms>Restart cmd no more then once in N ms, default0--reglob <ms>Glob files every N ms to track added files/dirs, default1000--check-md5Check md5 checksum of files and fire events only if checksum is changed--no-check-mtimeDon't check mtime of files and fire events only if mtime is changed--no-restart-on-errorDon't restart cmd if cmd crashed or exited with non 0 code--no-restart-on-successDon't restart cmd if cmd exited with 0 code--shell <shell cmd>Custom shell to use for running cmd--no-shellRun directly without shell--kill-signal <signals>Signal to send to child when process.kill(pid, signal), separated by comma--kill-timeout <ms>After which return with error--kill-retry-interval <intervals>Intervals between sending of kill signal, separated by comma--kill-retry-count <n>Number of retries--kill-check-interval <ms>Interval between checks if process is dead--kill-use-pgidUse PGID to get all children on mac/linux--kill-children-immediatelyKill children immediately, don't wait for parent to die--silentNo output from running cmd-v, --verboseLog when files are changed and cmd is restarted-V, --versionOutput version