Within your transform function, you manipulate the file object (an instance of Vinyl).
Passing files through the stream
To pass a file to the next plugin in the pipeline, you have two choices:
- Call
callback(null, file). - Call
this.push(file) and then call callback() without a second argument.
If your plugin generates multiple files from a single input (e.g., unzipping), call this.push(newFile) multiple times before calling the callback().
Handling different file content types
Vinyl files can contain contents in three forms. You should check the file type to avoid errors:
file.isNull(): The file has no contents (e.g., for rimraf or clean tasks). Simply return callback(null, file).file.isStream(): The contents are a Node.js stream.file.isBuffer(): The contents are a Node.js Buffer.
Error Handling
If an error occurs, pass the error as the first argument to the callback(error) function. For plugin-specific errors, it is recommended to use plugin-error.
var PluginError = require('plugin-error');
var PLUGIN_NAME = 'gulp-example';
module.exports = function() {
return through.obj(function(file, encoding, callback) {
if (file.isNull()) {
return callback(null, file);
}
if (file.isStream()) {
this.emit('error', new PluginError(PLUGIN_NAME, 'Streams not supported!'));
return callback();
} else if (file.isBuffer()) {
this.emit('error', new PluginError(PLUGIN_NAME, 'Buffers not supported!'));
return callback();
}
});
};