Skip to content

Commit

Permalink
Docs: Update watch() documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
janiceilene authored and phated committed Oct 19, 2018
1 parent ebb9818 commit 69c22f0
Showing 1 changed file with 92 additions and 64 deletions.
156 changes: 92 additions & 64 deletions docs/api/watch.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,105 +5,133 @@ hide_title: true
sidebar_label: watch()
-->

# `gulp.watch(globs[, opts][, fn])`
# watch()

Takes a path string, an array of path strings, a [glob][node-glob] string or an array of [glob][node-glob] strings as `globs` to watch on the filesystem. Also optionally takes `options` to configure the watcher and a `fn` to execute when a file changes.
Allows watching globs and running a task when a change occurs. Tasks are handled uniformly with the rest of the task system.

Returns an instance of [`chokidar`][chokidar].
## Usage

```js
gulp.watch('js/**/*.js', gulp.parallel('concat', 'uglify'));
const { watch } = require('gulp');

watch(['input/*.js', '!input/something.js'], function(cb) {
// body omitted
cb();
});
```

In the example, `gulp.watch` runs the function returned by `gulp.parallel` each
time a file with the `js` extension in `js/` is updated.
## Signature

```js
watch(globs, [options], [task])
```

## globs
Type: `String` or `Array`
### Parameters

A path string, an array of path strings, a [glob][node-glob] string or an array of [glob][node-glob] strings that indicate which files to watch for changes.
| parameter | type | note |
|:--------------:|:-----:|--------|
| globs <br> **(required)** | string <br> array | [Globs][globs-concepts] to watch on the file system. |
| options | object | Detailed in [Options][options-section] below. |
| task | function <br> string | A [task function][tasks-concepts] or composed task - generated by `series()` and `parallel()`. |

## opts
Type: `Object`
### Returns

* `delay` (milliseconds, default: `200`). The delay to wait before triggering the fn. Useful for waiting on many changes before doing the work on changed files, e.g. find-and-replace on many files.
* `queue` (boolean, default: `true`). Whether or not a file change should queue the fn execution if the fn is already running. Useful for a long running fn.
* `ignoreInitial` (boolean, default: `true`). If set to `false` the `fn` is called during [chokidar][chokidar] instantiation as it discovers the file paths. Useful if it is desirable to trigger the `fn` during startup. __Passed through to [chokidar][chokidar], but defaulted to `true` instead of `false`.__
An instance of [chokidar][chokidar-instance-section] for fine-grained control over your watch setup.

Options that are passed to [`chokidar`][chokidar].
### Errors

Commonly used options:
When a non-string or array with any non-strings is passed as `globs`, throws an error with the message, "Non-string provided as watch path".

* `ignored` ([anymatch](https://github.com/es128/anymatch)-compatible definition).
Defines files/paths to be excluded from being watched.
* `usePolling` (boolean, default: `false`). When `true` uses a watch method backed
by stat polling. Usually necessary when watching files on a network mount or on a
VMs file system.
* `cwd` (path string). The base directory from which watch paths are to be
derived. Paths emitted with events will be relative to this.
* `alwaysStat` (boolean, default: `false`). If relying upon the
[`fs.Stats`][fs stats] object
that may get passed as a second argument with `add`, `addDir`, and `change` events
when available, set this to `true` to ensure it is provided with every event. May
have a slight performance penalty.
When a string or array is passed as `task`, throws an error with the message, "watch task has to be a function (optionally generated by using gulp.parallel or gulp.series)".

Read about the full set of options in [`chokidar`'s README][chokidar].
### Options

## fn
Type: `Function`

If the `fn` is passed, it will be called when the watcher emits a `change`, `add` or `unlink` event. It is automatically debounced with a default delay of 200 milliseconds and subsequent calls will be queued and called upon completion. These defaults can be changed using the `options`.
| name | type | default | note |
|:-------:|:------:|-----------|--------|
| ignoreInitial | boolean | true | If false, the task is called during instantiation as file paths are discovered. Use to trigger the task during startup. <br> **Note:** This option is passed to [chokidar][chokidar-external] but is defaulted to `true` instead of `false`. |
| delay | number | 200 | The millisecond delay between a file change and task execution. Allows for waiting on many changes before executing a task, e.g. find-and-replace on many files. |
| queue | boolean | true | When true and the task is already running, any file changes will queue a single task execution. Keeps long running tasks from overlapping. |
| events | string <br> array | [ 'add', <br> 'change', <br> 'unlink' ] | The events being watched to trigger task execution. Can be `'add'`, `'addDir'`, `'change'`, `'unlink'`, `'unlinkDir'`, `'ready'`, and/or `'error'`. Additionally `'all'` is available, which represents all events other than `'ready'` and `'error'`. <br> _This option is passed directly to [chokidar][chokidar-external]._ |
| persistent | boolean | true | If false, the watcher will not keep the Node process running. Disabling this option is not recommended. <br> _This option is passed directly to [chokidar][chokidar-external]._ |
| ignored | array <br> string <br> RegExp <br> function | | Defines globs to be ignored. If a function is provided, it will be called twice per path - once with just the path, then with the path and the `fs.Stats` object of that file. <br> _This option is passed directly to [chokidar][chokidar-external]._ |
| followSymlinks | boolean | true | When true, changes to both symbolic links and the linked files trigger events. If false, only changes to the symbolic links trigger events. <br> _This option is passed directly to [chokidar][chokidar-external]._ |
| cwd | string | | The directory that will be combined with any relative path to form an absolute path. Is ignored for absolute paths. Use to avoid combining `globs` with `path.join()`. <br> _This option is passed directly to [chokidar][chokidar-external]._ |
| disableGlobbing | boolean | false | If true, all `globs` are treated as literal path names, even if they have special characters. <br> _This option is passed directly to [chokidar][chokidar-external]._ |
| usePolling | boolean | false | When false, the watcher will use `fs.watch()` (or [fsevents][fsevents-external] on Mac) for watching. If true, use `fs.watchFile()` polling instead - needed for successfully watching files over a network or other non-standard situations. Overrides the `useFsEvents` default. <br> _This option is passed directly to [chokidar][chokidar-external]._ |
| interval | number | 100 | Combine with `usePolling: true`. Interval of file system polling. <br> _This option is passed directly to [chokidar][chokidar-external]._ |
| binaryInterval | number | 300 | Combine with `usePolling: true`. Interval of file system polling for binary files. <br> _This option is passed directly to [chokidar][chokidar-external]._ |
| useFsEvents | boolean | true | When true, uses fsevents for watching if available. If explicitly set to true, supersedes the `usePolling` option. If set to false, automatically sets `usePolling` to true. <br> _This option is passed directly to [chokidar][chokidar-external]._ |
| alwaysStat | boolean | false | If true, always calls `fs.stat()` on changed files - will slow down file watcher. The `fs.Stat` object is only available if you are using the chokidar instance directly. <br> _This option is passed directly to [chokidar][chokidar-external]._ |
| depth | number | | Indicates how many nested levels of directories will be watched. <br> _This option is passed directly to [chokidar][chokidar-external]._ |
| awaitWriteFinish | boolean | false | Do not use this option, use `delay` instead. <br> _This option is passed directly to [chokidar][chokidar-external]._ |
| ignorePermissionErrors | boolean | false | Set to true to watch files that don't have read permissions. Then, if watching fails due to EPERM or EACCES errors, they will be skipped silently. <br> _This option is passed directly to [chokidar][chokidar-external]._ |
| atomic | number | 100 | Only active if `useFsEvents` and `usePolling` are false. Automatically filters out artifacts that occur from "atomic writes" by some editors. If a file is re-added within the specified milliseconds of being deleted, a change event - instead of unlink then add - will be emitted. <br> _This option is passed directly to [chokidar][chokidar-external]._ |

The `fn` is passed a single argument, `callback`, which is a function that must be called when work in the `fn` is complete. Instead of calling the `callback` function, [async completion][async-completion] can be signalled by:
* Returning a `Stream` or `EventEmitter`
* Returning a `Child Process`
* Returning a `Promise`
* Returning an `Observable`
## Chokidar instance

Once async completion is signalled, if another run is queued, it will be executed.
The `watch()` method returns the underlying instance of [chokidar][chokidar-external], providing fine-grained control over your watch setup. Most commonly used to register individual event handlers that provide the `path` or `stats` of the changed files.

`gulp.watch` returns a wrapped [chokidar] FSWatcher object. Listeners can also be set directly for any of [chokidar]'s events, such as `addDir`, `unlinkDir`, and `error`. You must set listeners directly to get
access to chokidar's callback parameters, such as `path`.
**When using the chokidar instance directly, you will not have access to the task system integrations, including async completion, queueing, and delay.**

```js
var watcher = gulp.watch('js/**/*.js', gulp.parallel('concat', 'uglify'));
const { watch } = require('gulp');

const watcher = watch(['input/*.js']);

watcher.on('change', function(path, stats) {
console.log('File ' + path + ' was changed');
console.log(`File ${path} was changed`);
});

watcher.on('add', function(path, stats) {
console.log(`File ${path} was added`);
});

watcher.on('unlink', function(path) {
console.log('File ' + path + ' was removed');
watcher.on('unlink', function(path, stats) {
console.log(`File ${path} was removed`);
});

watcher.close();
```

### path
Type: `String`

Path to the file. If `opts.cwd` is set, `path` is relative to it.
`watcher.on(eventName, eventHandler)`

Registers `eventHandler` functions to be called when the specified event occurs.

| parameter | type | note |
|:--------------:|:-----:|--------|
| eventName | string | The events that may be watched are `'add'`, `'addDir'`, `'change'`, `'unlink'`, `'unlinkDir'`, `'ready'`, `'error'`, or `'all'`. |
| eventHandler | function | Function to be called when the specified event occurs. Arguments detailed in the table below. |

### stats
Type: `Object`
| argument | type | note |
|:-------------:|:-----:|--------|
| path | string | The path of the file that changed. If the `cwd` option was set, the path will be made relative by removing the `cwd`. |
| stats | object | An [fs.Stat][fs-stats-concepts] object, but could be `undefined`. If the `alwaysStat` option was set to `true`, `stats` will always be provided. |

[File stats][fs stats] object when available.
Setting the `alwaysStat` option to `true` will ensure that a file stat object will be
provided.
`watcher.close()`

## watcher methods
Shuts down the file watcher. Once shut down, no more events will be emitted.

### watcher.close()
`watcher.add(globs)`

Shuts down the file watcher.
Adds additional globs to an already-running watcher instance.

### watcher.add(glob)
| parameter | type | note |
|:-------------:|:-----:|--------|
| globs | string <br> array | The additional globs to be watched. |

Watch additional glob (or array of globs) with an already-running watcher instance.
`watcher.unwatch(globs)`

### watcher.unwatch(glob)
Removes globs that are being watched, while the watcher continues with the remaining paths.

Stop watching a glob (or array of globs) while leaving the watcher running and
emitting events for the remaining paths it is watching.
| parameter | type | note |
|:-------------:|:-----:|--------|
| globs | string <br> array | The globs to be removed. |

[chokidar]: https://github.com/paulmillr/chokidar
[node-glob]: https://github.com/isaacs/node-glob
[fs stats]: https://nodejs.org/api/fs.html#fs_class_fs_stats
[async-completion]: https://github.com/gulpjs/async-done#completion-and-error-resolution
[chokidar-instance-section]: #chokidar-instance
[tasks-concepts]: concepts.md#tasks
[globs-concepts]: concepts.md#globs
[fs-stats-concepts]: concepts.md#file-system-stats
[chokidar-external]: https://github.com/paulmillr/chokidar
[fsevents-external]: https://github.com/strongloop/fsevents

0 comments on commit 69c22f0

Please # to comment.