Gulp writing a plugin
last modified November 15, 2026
In this article we write a Gulp 5 plugin. The plugin is a function that returns an object-mode Transform stream; it
receives Vinyl file objects, changes them and passes them on. We handle the different kinds of files, report errors with PluginError
and test the plugin without Gulp.
What a plugin is
A Gulp plugin is not a special object. It is a function that returns a stream, and the stream is placed in a pipeline between
src and dest. The stream works in object mode: it does not read bytes, but file objects created by
src, described in Gulp Vinyl. The plugin receives a file, reads or changes its
contents and path, and passes the file to the next stream.
Older plugins use the through2 package, which only wraps a Transform. Since Node.js has a good
Transform class, we use it directly and avoid the dependency.
Installing the project
We create an ES module project and install Gulp, plugin-error for the errors and vinyl for the tests.
The plugin goes to the plugins directory; a published plugin would be a package of its own.
$ mkdir gulp-plugin $ cd gulp-plugin $ npm init -y $ npm pkg set type=module $ npm i -D gulp plugin-error vinyl $ mkdir src plugins
The banner plugin
Our plugin adds a comment with a given text to the beginning of each file. The exported function checks its parameter and
returns the Transform stream. The transform method is called for each file, with the file, the encoding
(not used for objects) and a callback.
import { Transform } from 'node:stream';
import PluginError from 'plugin-error';
const PLUGIN_NAME = 'banner';
export default function banner(text) {
if (typeof text !== 'string' || text === '') {
throw new PluginError(PLUGIN_NAME, 'A banner text is required');
}
return new Transform({
objectMode: true,
transform(file, encoding, callback) {
if (file.isNull()) {
return callback(null, file);
}
if (file.isStream()) {
return callback(new PluginError(PLUGIN_NAME, 'Streams are not supported'));
}
const content = file.contents.toString('utf8');
file.contents = Buffer.from(`/* ${text} */\n${content}`);
callback(null, file);
}
});
}
A file can be in three states. If it is null (file.isNull()), it has no contents: it is a directory, or
it was read with read: false; the plugin passes it on unchanged. If it is a stream
(file.isStream(), when src has the buffer: false option), the contents are a readable stream, and
our plugin does not support them and reports an error. Otherwise it is a buffer: we convert it to a string, add the banner
and assign a new Buffer. The callback is called with an error, or with null and the file to pass it on; the
shorter form callback(null, file) is the same as calling this.push(file) and then callback().
Using the plugin
The plugin is used like any other: we import it and put it in a pipe. The project has two small scripts in src.
import { src, dest } from 'gulp';
import { pipeline } from 'node:stream/promises';
import banner from './plugins/banner.js';
export function build() {
return src('src/*.js')
.pipe(banner('Copyright 2026 ZetCode'))
.pipe(dest('dist'));
}
export function streams() {
return src('src/*.js', { buffer: false })
.pipe(banner('Copyright 2026 ZetCode'))
.pipe(dest('dist'));
}
export function noText() {
return src('src/*.js')
.pipe(banner(''))
.pipe(dest('dist'));
}
export function safe() {
return pipeline(
src('src/*.js', { buffer: false }),
banner('Copyright 2026 ZetCode'),
dest('dist')
);
}
The build task is the normal use. The other tasks serve to show the errors and are explained below.
We run the first one and print a result.
$ cat src/a.js
console.log("a");
$ npx gulp build
[13:58:05] Using gulpfile ~/Documents/prog/js/gulp-plugin/gulpfile.mjs
[13:58:05] Starting 'build'...
[13:58:05] Finished 'build' after 16 ms
$ cat dist/a.js
/* Copyright 2026 ZetCode */
console.log("a");
Reporting errors
A plugin reports problems with PluginError, which takes the name of the plugin and a message. Gulp prints the name, so the
user knows which plugin failed. There are two kinds of errors. A wrong option is detected when the plugin function is called,
so the error is thrown; a problem with a file is passed to the callback of transform. In both cases the task fails and
gulp exits with the status 1. The noText task calls banner(''), and the streams task uses
buffer: false, so the files are streams.
$ npx gulp noText; echo "exit status: $?"
[13:58:06] Using gulpfile ~/Documents/prog/js/gulp-plugin/gulpfile.mjs
[13:58:06] Starting 'noText'...
exit status: 1
[13:58:06] 'noText' errored after 4.36 ms
[13:58:06] Error in plugin "banner"
Message:
A banner text is required
$ npx gulp streams; echo "exit status: $?"
[13:58:06] Using gulpfile ~/Documents/prog/js/gulp-plugin/gulpfile.mjs
[13:58:06] Starting 'streams'...
exit status: 1
[13:58:06] 'streams' errored after 9.84 ms
[13:58:06] Error in plugin "banner"
Message:
Streams are not supported
Errors in a long pipeline
The .pipe() method does not forward errors from the middle of a chain. In our example the error from the callback
was reported, but an error that is raised later, for example after an asynchronous operation, can make Gulp print "did not complete"
instead. The safe way is the pipeline function from node:stream/promises, which watches all streams and rejects when any
of them fails. The task returns the promise. This was described in Gulp error handling.
export function safe() {
return pipeline(
src('src/*.js', { buffer: false }),
banner('Copyright 2026 ZetCode'),
dest('dist')
);
}
The task fails with the error of the plugin, as before.
$ npx gulp safe; echo "exit status: $?"
[13:58:06] Using gulpfile ~/Documents/prog/js/gulp-plugin/gulpfile.mjs
[13:58:06] Starting 'safe'...
exit status: 1
[13:58:06] 'safe' errored after 13 ms
[13:58:06] Error in plugin "banner"
Message:
Streams are not supported
Testing the plugin
A plugin can be tested without Gulp. We create a Vinyl file, write it to the stream and wait for the data event, which
delivers the file, or for the error event. The built-in test runner of Node.js and the node:assert module are
enough. The tests cover a buffer, a null file and a wrong option.
import test from 'node:test';
import assert from 'node:assert/strict';
import Vinyl from 'vinyl';
import banner from './banner.js';
function run(file, text = 'Hi') {
return new Promise((resolve, reject) => {
const stream = banner(text);
stream.on('data', resolve);
stream.on('error', reject);
stream.write(file);
});
}
test('adds the banner to a buffer file', async () => {
const file = new Vinyl({ path: '/src/a.js', contents: Buffer.from('let a;') });
const result = await run(file);
assert.equal(result.contents.toString(), '/* Hi */\nlet a;');
});
test('passes null files through', async () => {
const file = new Vinyl({ path: '/src/dir' });
const result = await run(file);
assert.ok(result.isNull());
});
test('rejects an empty text', () => {
assert.throws(() => banner(''), /banner text is required/);
});
The helper function run wraps the stream in a promise, which makes the tests short.
We run the tests with the spec reporter.
$ node --test --test-reporter=spec plugins/banner.test.js ✔ adds the banner to a buffer file (1.398618ms) ✔ passes null files through (0.31335ms) ✔ rejects an empty text (0.574801ms) ℹ tests 3 ℹ suites 0 ℹ pass 3 ℹ fail 0 ℹ cancelled 0 ℹ skipped 0 ℹ todo 0 ℹ duration_ms 65.016634
Source
Writing a plugin in the Gulp documentation, Node.js Transform streams, plugin-error on npm
In this article we have written a Gulp 5 plugin: a Transform stream in object mode, which handles null, buffer and stream
files, reports errors with PluginError, and is tested with Vinyl files without running Gulp. See also the Gulp Vinyl and Gulp src and dest tutorials.
Author
List all Gulp tutorials.