ZetCode

Gulp watch

last modified November 15, 2026

In this article we rebuild a project automatically with the Gulp watch function. We watch files with globs, look at the events that trigger a task, and tune the behaviour with the events, delay, queue, ignoreInitial, and ignored options.

Gulp watch

The watch function monitors files and runs a task when they change. Without it we would have to run Gulp by hand after every edit. The function takes a glob or an array of globs, an optional options object, and the task to run. It returns a watcher, an instance of the chokidar file watcher, that emits events we can listen to. See the Gulp src and dest tutorial for more on globs.

Installing the project

We create a project and install gulp and gulp-clean-css. The stylesheets are in the src/css directory.

$ mkdir gulp-watch
$ cd gulp-watch
$ npm init -y
$ npm i -D gulp gulp-clean-css
$ mkdir -p src/css

Watching CSS files

The styles task minifies the CSS files from src/css, and the watchStyles task watches the same files.

basic.mjs
import { src, dest, watch } from 'gulp';
import cleanCSS from 'gulp-clean-css';

export function styles() {

    return src('src/css/*.css')
        .pipe(cleanCSS())
        .pipe(dest('dist/css'));
}

export function watchStyles() {

    watch('src/css/*.css', styles);
}

The gulpfile has the build task and a task that watches the files the build reads.

export function watchStyles() {

    watch('src/css/*.css', styles);
}

The watch call registers the watcher and returns immediately; the watcher keeps the Node.js process alive, so the task never finishes and we stop it with Ctrl+C. The watched task is the same function that runs from the command line, so the build logic exists only once.

We start the watcher and append a rule to site.css from another terminal. The watcher reacts with a rebuild; Gulp does not run styles at start.

$ npx gulp --gulpfile basic.mjs watchStyles
[12:45:07] Using gulpfile ~/Documents/prog/js/gulp-watch/basic.mjs
[12:45:07] Starting 'watchStyles'...
[12:45:09] Starting 'styles'...
[12:45:09] Finished 'styles' after 25 ms

Several quick changes

Editors often write a file several times in a short time, and a build tool that reacts to each write would run too often. Gulp waits for 200 milliseconds after a change before it starts the task, and changes that arrive in that period are collapsed into one run.

In the next experiments the task is slower: slowBuild pretends to work for 800 ms. The same gulpfile defines all the watch tasks below.

options.mjs
import { watch } from 'gulp';
import { setTimeout as sleep } from 'node:timers/promises';

async function slowBuild() {

    console.log('build started');
    await sleep(800);
    console.log('build finished');
}

export function events() {

    const watcher = watch('src/css/*.css', { events: ['add', 'unlink'] }, slowBuild);

    watcher.on('add', path => console.log(`added: ${path}`));
    watcher.on('change', path => console.log(`changed: ${path}`));
    watcher.on('unlink', path => console.log(`removed: ${path}`));
}

export function delayed() {

    watch('src/css/*.css', { delay: 500 }, slowBuild);
}

export function queued() {

    watch('src/css/*.css', slowBuild);
}

export function notQueued() {

    watch('src/css/*.css', { queue: false }, slowBuild);
}

export function initial() {

    watch('src/css/*.css', { ignoreInitial: false }, slowBuild);
}

The tasks differ only in the options passed to watch. The default behaviour is shown by queued. We append a line to the stylesheet, another 300 ms later, and a third 100 ms after that. The first change starts a build, and the two later ones arrive while it runs. They are queued and cause exactly one more build, not two.

$ npx gulp --gulpfile options.mjs queued
[12:45:13] Using gulpfile ~/Documents/prog/js/gulp-watch/options.mjs
[12:45:13] Starting 'queued'...
[12:45:15] Starting 'slowBuild'...
build started
build finished
[12:45:16] Finished 'slowBuild' after 803 ms
[12:45:16] Starting 'slowBuild'...
build started
build finished
[12:45:17] Finished 'slowBuild' after 802 ms

The queue option

The queue option controls what happens to changes that arrive while the task is running. It is true by default, as shown above. With queue: false such changes are ignored, so with the same three edits the task runs only once. This is fine only when the running task has not yet read the changed files; otherwise the last edit is lost until the next change.

$ npx gulp --gulpfile options.mjs notQueued
[12:45:19] Using gulpfile ~/Documents/prog/js/gulp-watch/options.mjs
[12:45:19] Starting 'notQueued'...
[12:45:21] Starting 'slowBuild'...
build started
build finished
[12:45:22] Finished 'slowBuild' after 802 ms

The delay option

The delay option sets the waiting time, in milliseconds, after a change before the task starts. The default is 200. With a longer delay, a burst of changes is merged into one run. In the delayed task the delay is 500 ms, long enough to cover all three edits, so the task runs once after the last of them.

$ npx gulp --gulpfile options.mjs delayed
[12:45:25] Using gulpfile ~/Documents/prog/js/gulp-watch/options.mjs
[12:45:25] Starting 'delayed'...
[12:45:28] Starting 'slowBuild'...
build started
build finished
[12:45:29] Finished 'slowBuild' after 803 ms

The events option

By default every kind of change runs the task: a file was added (add), changed (change), or removed (unlink). The events option restricts which events trigger it. The events task runs the build only when a file is added or removed. The watcher emits all events anyway, so we can listen to them with on and log each of them.

We create new.css, change it, and remove it. The addition starts a build and the removal starts another one. The change is logged, but it does not start a build.

$ npx gulp --gulpfile options.mjs events
[12:45:31] Using gulpfile ~/Documents/prog/js/gulp-watch/options.mjs
[12:45:31] Starting 'events'...
added: src/css/new.css
[12:45:34] Starting 'slowBuild'...
build started
changed: src/css/new.css
build finished
[12:45:35] Finished 'slowBuild' after 803 ms
removed: src/css/new.css
[12:45:35] Starting 'slowBuild'...
build started
build finished
[12:45:36] Finished 'slowBuild' after 802 ms

The ignoreInitial option

The watcher by default reports only changes that happen after it has started. The ignoreInitial option is true by default; setting it to false makes the watcher report every file that exists at the start as an added file, which runs the task once at startup. This is a convenient way to build the project and start watching in a single task. The initial task of the gulpfile uses it.

$ npx gulp --gulpfile options.mjs initial
[12:45:38] Using gulpfile ~/Documents/prog/js/gulp-watch/options.mjs
[12:45:38] Starting 'initial'...
[12:45:38] Starting 'slowBuild'...
build started
build finished
[12:45:39] Finished 'slowBuild' after 803 ms

A complete watch task

A real project watches several kinds of files. The final gulpfile builds styles and scripts, and the default task runs the build once and then starts the watchers. Each watcher runs only the task it is responsible for. The ignored option excludes editor temporary files with the .tmp extension. Here gulp-terser is installed in addition to gulp-clean-css.

gulpfile.mjs
import { src, dest, watch, series, parallel } from 'gulp';
import cleanCSS from 'gulp-clean-css';
import terser from 'gulp-terser';

export function styles() {

    return src('src/css/*.css')
        .pipe(cleanCSS())
        .pipe(dest('dist/css'));
}

export function scripts() {

    return src('src/js/*.js')
        .pipe(terser())
        .pipe(dest('dist/js'));
}

export const build = parallel(styles, scripts);

function watchFiles() {

    const options = { ignored: '**/*.tmp' };

    watch('src/css/**/*', options, styles);
    watch('src/js/**/*', options, scripts);
}

export default series(build, watchFiles);

The watchers are created in a private function, which is used only by the default task.

watch('src/css/**/*', options, styles);
watch('src/js/**/*', options, scripts);

The watch functions are not returned from watchFiles; the function only registers them. The series composition guarantees that the first build is finished before the watching starts. In the experiment we change a CSS file, then a JavaScript file, and finally a .tmp file. Each of the first two edits runs its own task and the third is ignored.

$ npx gulp
[12:45:44] Using gulpfile ~/Documents/prog/js/gulp-watch/gulpfile.mjs
[12:45:44] Starting 'default'...
[12:45:44] Starting 'styles'...
[12:45:44] Starting 'scripts'...
[12:45:44] Finished 'styles' after 38 ms
[12:45:44] Finished 'scripts' after 39 ms
[12:45:44] Starting 'watchFiles'...
[12:45:47] Starting 'styles'...
[12:45:47] Finished 'styles' after 12 ms
[12:45:47] Starting 'scripts'...
[12:45:47] Finished 'scripts' after 15 ms

Source

Gulp watch API, chokidar on GitHub, glob-watcher on GitHub

In this article we have watched files with Gulp 5. We rebuilt styles and scripts on change and tuned the watcher with the events, delay, queue, ignoreInitial, and ignored options. See also the Gulp Browsersync and Gulp Sass tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Gulp tutorials.