ZetCode

Gulp src and dest

last modified November 15, 2026

In this article we look at the two functions that every Gulp task is built on: src, which reads files, and dest, which writes them. We use globs and negated globs, control the output paths with the base option, work with dotfiles, handle missing files, write to computed directories, and build incrementally with since.

src and dest

src takes a glob or an array of globs and returns a stream of virtual file objects. dest takes a directory and writes the files of the stream into it. Between the two, plugins transform the files. A task that contains only src and dest is a plain copy. This article is about that copy, because most of the surprises in a Gulp build, such as unexpected output paths or missing files, are caused by the arguments of these two functions. The Gulp getting started tutorial introduces them.

The example project

The example project has a small source tree: a HTML file, scripts, a stylesheet, an image, and a dotfile named .env. Every task of the gulpfile reads from this tree and writes to its own directory under out, so we can compare the results. The image is the same 32 x 32 pixel PNG file that we used in the Gulp 5 tutorial.

$ mkdir -p gulp-srcdest/src/{js,css,img}
$ cd gulp-srcdest
$ npm init -y
$ npm i -D gulp
$ echo '<h1>Home</h1>' > src/index.html
$ echo 'export const app = 1;' > src/js/app.js
$ echo 'export const util = 2;' > src/js/util.js
$ echo 'test("util");' > src/js/util.test.js
$ echo 'body { margin: 0; }' > src/css/site.css
$ echo 'secret' > src/.env
$ find src | sort
src
src/css
src/css/site.css
src/.env
src/img
src/img/logo.png
src/index.html
src/js
src/js/app.js
src/js/util.js
src/js/util.test.js

The gulpfile

The gulpfile contains one task for each topic of this article. We explain them in the following sections.

gulpfile.mjs
import { src, dest, watch, series, lastRun, symlink } from 'gulp';

export function everything() {

    return src('src/**/*', { encoding: false }).pipe(dest('out/everything'));
}

export function noTests() {

    return src(['src/js/*.js', '!src/js/*.test.js']).pipe(dest('out/no-tests'));
}

export function flat() {

    return src('src/js/*.js').pipe(dest('out/flat'));
}

export function withBase() {

    return src('src/js/*.js', { base: 'src' }).pipe(dest('out/with-base'));
}

export function dotfiles() {

    return src('src/**/*', { dot: true, encoding: false }).pipe(dest('out/dotfiles'));
}

export function ignored() {

    return src('src/**/*.{js,css}', { ignore: '**/*.test.js' }).pipe(dest('out/ignored'));
}

export function incremental() {

    return src('src/js/*.js', { since: lastRun(incremental) })
        .on('data', file => console.log(`  processing ${file.relative}`))
        .pipe(dest('out/incremental'));
}

export function missing() {

    return src('src/js/missing.js').pipe(dest('out/missing'));
}

export function missingAllowed() {

    return src('src/js/missing.js', { allowEmpty: true }).pipe(dest('out/missing'));
}

export function links() {

    return src('src/js/*.js').pipe(symlink('out/links'));
}

function watchScripts() {

    watch('src/js/*.js', incremental);
}

export const dev = series(incremental, watchScripts);

export function byType() {

    return src(['src/js/*.js', 'src/css/*.css', 'src/index.html'])
        .pipe(dest(file => file.extname === '.html' ? 'out/by-type' : `out/by-type/${file.extname.slice(1)}`));
}

export function keepExisting() {

    return src('src/js/app.js').pipe(dest('out/keep', { overwrite: false }));
}

Because each task has its own destination, running one of them never disturbs the results of another. To keep the output short, we run the tasks with the --silent option, which suppresses the log lines of Gulp itself.

Globs

A glob is a pattern that matches file paths. The character * matches any characters within one directory level, ** matches any number of directory levels, ? matches one character, and braces list alternatives, as in *.{js,css}. A glob is relative to the working directory.

return src('src/**/*', { encoding: false }).pipe(dest('out/everything'));

The pattern src/**/* matches every file in the tree. The directory structure below the part of the glob before the first wildcard, here src, is preserved in the output. The image is copied with encoding: false, as explained in the Gulp 5 tutorial. Note that the dotfile .env is not in the output: patterns do not match names that start with a dot unless we ask for them.

$ npx gulp --silent everything
$ find out/everything -type f | sort
out/everything/css/site.css
out/everything/img/logo.png
out/everything/index.html
out/everything/js/app.js
out/everything/js/util.js
out/everything/js/util.test.js

Negated globs and the ignore option

A glob that starts with an exclamation mark removes the matching files from the result of the earlier globs in the array, so the order matters. The ignore option achieves the same with a separate setting.

src(['src/js/*.js', '!src/js/*.test.js'])

src('src/**/*.{js,css}', { ignore: '**/*.test.js' })

Both tasks leave the test script out. The noTests task writes the two remaining scripts. The ignored task selects scripts and stylesheets from the whole tree and again leaves out the test.

$ npx gulp --silent noTests ignored
$ find out/no-tests out/ignored -type f | sort
out/ignored/css/site.css
out/ignored/js/app.js
out/ignored/js/util.js
out/no-tests/app.js
out/no-tests/util.js

The base option

Every file object remembers its base, the part of the path that is not copied to the output. By default it is the part of the glob before the first wildcard. For src/js/*.js it is src/js, so the files are written directly into the destination directory. If we want to keep the js directory, we set the base to src.

src('src/js/*.js', { base: 'src' }).pipe(dest('out/with-base'));

The flat task uses the default base and the withBase task sets it explicitly. The second task reproduces the directory js below the destination. The option is useful when we select files from different directories and want to keep their relative paths.

$ npx gulp --silent flat withBase
$ find out/flat out/with-base -type f | sort
out/flat/app.js
out/flat/util.js
out/flat/util.test.js
out/with-base/js/app.js
out/with-base/js/util.js
out/with-base/js/util.test.js

Dotfiles

To include files whose names start with a dot, we set the dot option. Without it the .env file of our project is skipped by wildcards.

src('src/**/*', { dot: true, encoding: false }).pipe(dest('out/dotfiles'));

Now the dotfile is part of the output. The option also makes patterns match hidden directories such as .git, which is rarely wanted; in a real project we combine it with a negated glob.

$ npx gulp --silent dotfiles
$ find out/dotfiles -type f | sort
out/dotfiles/css/site.css
out/dotfiles/.env
out/dotfiles/img/logo.png
out/dotfiles/index.html
out/dotfiles/js/app.js
out/dotfiles/js/util.js
out/dotfiles/js/util.test.js

Missing files

A glob without wildcards names one file. When that file does not exist, the task fails, because this is almost always a typing error. A pattern with wildcards that matches nothing is not an error. The allowEmpty option turns the failure of a single file into a successful empty result.

src('src/js/missing.js', { allowEmpty: true })

The first task fails with the message "File not found with singular glob" and the exit status 1. Gulp suggests the option in the message. The second task uses allowEmpty and finishes without writing anything.

$ npx gulp missing 2>&1 | head -4
[12:46:24] Using gulpfile ~/Documents/prog/js/gulp-srcdest/gulpfile.mjs
[12:46:24] Starting 'missing'...
[12:46:24] 'missing' errored after 6.49 ms
[12:46:24] Error: File not found with singular glob: ~/Documents/prog/js/gulp-srcdest/src/js/missing.js (if this was purposeful, use `allowEmpty` option)
$ npx gulp missing >/dev/null 2>&1; echo $?
1
$ npx gulp missingAllowed
[12:46:25] Using gulpfile ~/Documents/prog/js/gulp-srcdest/gulpfile.mjs
[12:46:25] Starting 'missingAllowed'...
[12:46:25] Finished 'missingAllowed' after 6.6 ms

Computed destination directories

The argument of dest can also be a function. Gulp calls it for each file and uses the returned string as the output directory, so the destination can depend on the file. In byType HTML files go to the root and the other files into a directory named after their extension.

dest(file => file.extname === '.html' ? 'out/by-type' : `out/by-type/${file.extname.slice(1)}`)

The result has the HTML file in the root and the scripts and the stylesheet in separate directories.

$ npx gulp --silent byType
$ find out/by-type -type f | sort
out/by-type/css/site.css
out/by-type/index.html
out/by-type/js/app.js
out/by-type/js/util.js
out/by-type/js/util.test.js

Keeping existing files

By default dest overwrites files that already exist. With overwrite: false it leaves them alone. In the experiment we run the task, change the copy in the output directory and the source file, and run the task again. The edited copy survives the second run.

src('src/js/app.js').pipe(dest('out/keep', { overwrite: false }));

The output shows the content of the copy after the second run: it is the text we wrote ourselves, not the new content of the source file.

$ npx gulp --silent keepExisting
$ echo edited > out/keep/app.js
$ echo 'export const app = 99;' > src/js/app.js
$ npx gulp --silent keepExisting
$ cat out/keep/app.js
edited

Incremental builds with since

The since option of src selects only files that were modified after a given time. The lastRun function returns the time when a task last completed, so since: lastRun(task) processes just the files that changed since the previous run. The value is kept in memory, so the trick works within one Gulp process, typically together with watch.

export function incremental() {

    return src('src/js/*.js', { since: lastRun(incremental) })
        .on('data', file => console.log(`  processing ${file.relative}`))
        .pipe(dest('out/incremental'));
}

The dev task runs incremental once and then watches the scripts. At the first run every file is processed, because lastRun returns undefined. When we touch util.js, only that file is processed.

$ npx gulp dev
[12:46:28] Using gulpfile ~/Documents/prog/js/gulp-srcdest/gulpfile.mjs
[12:46:28] Starting 'dev'...
[12:46:28] Starting 'incremental'...
  processing app.js
  processing util.js
  processing util.test.js
[12:46:28] Finished 'incremental' after 13 ms
[12:46:28] Starting 'watchScripts'...
[12:46:30] Starting 'incremental'...
  processing util.js
[12:46:30] Finished 'incremental' after 6.35 ms

Symbolic links

The symlink function of Gulp is an alternative to dest. It creates symbolic links to the source files instead of copying them, which is fast and keeps the output in sync with the sources.

src('src/js/*.js').pipe(symlink('out/links'));

The long listing shows that the files in the output directory are links to the sources.

$ npx gulp --silent links
$ ls -l out/links | awk 'NR>1 {print $1, $9, $10, $11}'
lrwxrwxrwx app.js -> ~/Documents/prog/js/gulp-srcdest/src/js/app.js
lrwxrwxrwx util.js -> ~/Documents/prog/js/gulp-srcdest/src/js/util.js
lrwxrwxrwx util.test.js -> ~/Documents/prog/js/gulp-srcdest/src/js/util.test.js

Source maps

Both functions have a sourcemaps option. When src reads the files with sourcemaps: true and dest writes them with a path such as '.', Gulp loads existing source maps and writes the maps produced by plugins such as gulp-terser or gulp-sass next to the output files. The Gulp Terser and Gulp Sass tutorials use it.

Source

Gulp src API, Gulp dest API, Gulp symlink API, Gulp lastRun API, Explaining globs

In this article we have read and written files with Gulp 5: globs and negated globs, the base, dot, ignore, allowEmpty, and since options, computed destinations, and symbolic links. See also the Gulp watch and Gulp error handling 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.