SSCCE:
gulp.task('foo', [], function() {
var barFiles = getBarFiles();
var bazFiles = getBazFiles();
var barStream, bazStream;
if (barFiles && barFiles.length > 0) {
barStream = gulp.src(barFiles);
}
if (bazStream && bazStream.length > 0) {
bazStream = gulp.src(bazStream);
}
return eventStream
.merge(barStream, bazStream)
.pipe(g.concat('bar-and-baz'))
.pipe(gulp.dest('./foo-output/'));
});
getBarFiles()
or getBazFiles()
may return an empty array,
which is not allowed by gulp.src()
: Error: Invalid glob argument
,
hence the need to wrap the creation of the stream with an if
condition.
So the question is, how do I create an empty stream, so that it can be merged with the other empty on non-empty stream?
Streams in Gulp provide us with a way to convert files into object that can flow through the pipeline without having to be written to disk after each step. The same workflow would look like this in Gulp: Start reading src/*.
src() Creates a stream for reading Vinyl objects from the file system.
Gulp is a task runner that uses Node. js as a platform. Gulp purely uses the JavaScript code and helps to run front-end tasks and large-scale web applications. It builds system automated tasks like CSS and HTML minification, concatenating library files, and compiling the SASS files.
How about using:
return gulp.src('.');
For newer Gulp its possible you will need to add allowEmpty: true
option as follows:
return gulp.src('.', {allowEmpty: true});
As I assume it should just pass current directory in the stream with no actions on it. Works for me.
A function for creating an empty stream for use in gulp (gleaned from vinyl-fs source) is this:
var through2 = require('through2');
function createEmptyStream() {
var pass = through2.obj();
process.nextTick(pass.end.bind(pass));
return pass;
}
If you make barFiles = createEmptyStream() in the example, it is functionally the same.
Current version of gulp (3.9.1) and vinyl-fs (0.3.0) on 2016-03-05 allows for an empty src array (from my testing). It uses something similar to the above to create an empty stream. Your example works (mostly as-is) in current versions:
var eventStream = require('event-stream');
var gulp = require('gulp');
var g = require('gulp-load-plugins')();
function getBarFiles() {
return [
];
}
function getBazFiles() {
return [
'baz.txt'
];
}
gulp.task('foo', [], function() {
var barFiles = getBarFiles();
var bazFiles = getBazFiles();
var barStream = gulp.src(barFiles);
var bazStream = gulp.src(bazFiles);
return eventStream
.merge(barStream, bazStream)
.pipe(g.concat('bar-and-baz.txt'))
.pipe(gulp.dest('./'));
});
gulp.task('default', [ 'foo' ]);
The file bar-and-baz.txt is a concatenation of the contents of all files in the globs returned from those two functions. An empty list of globs is accepted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With