Gulp: on("end", fn ()) does not appear to be working correctly

Created on 4 May 2016  路  7Comments  路  Source: gulpjs/gulp

Someone raised an issue in gulp-jasmine (sindresorhus/gulp-jasmine#69) about the end event, and it seems to be caused by gulp:

gulp.task("default", function (callback) {
    gulp.src("test.spec.js")
        .on("end", function () {
            console.log("We're done!");
            callback();
        });
});

works with [email protected] but stopped working with [email protected].

Returning the pipe:

gulp.task("default", function () {
    return gulp.src("test.spec.js")
        .on("end", function () {
            console.log("We're done!");
        });
});

works as expected. Not sure if I'm missing something (I rarely use callbacks).

Most helpful comment

You can return your stream or attach an on('data', noop) handler.

All 7 comments

This is how streams work. How does it end if you aren't piping it somewhere? The reason it works when you return it is because the underlying library (orchestrator) attaches an on('data') handler which causes the stream to flow.

Thanks for the quick answer.

Maybe I simplified my example too much (but there was still a difference in behaviour between 3.7 and 3.8). How about this example:

var gulp = require("gulp");
var through = require("through2");

var foo = through.obj(function (file, enc, cb) {
    console.log(file);
    cb(null, file);
});

gulp.task("default", function (cb) {
    gulp.src("test.spec.js")
        .pipe(foo)
        .on("end", function () {
            console.log("We're done!");
            cb();
        });
});

Technically a stream that ends with a transform stream (through2) won't end either. You have to end on a Writable stream. I'm also wondering why you aren't using 3.9.1

I am using 3.9.1, I'm trying to understand why code that worked in 3.7 doesn't work anymore, and 3.8 is the version where it stopped working.

My understanding from what you're saying is that the end event is only emitted by the drain (i.e. gulp.dest), so I'll have to force and emit.end() in the flush callback to simulate that, since gulp-jasmine is never really writing anything.

You can return your stream or attach an on('data', noop) handler.

I pretty much always return my streams, but I need a generic solution for gulp-jasmine. Emitting the 'end' event in the flush function did the trick. Thanks for taking the time to help me.

@jbblanchet that's a really bad way to solve the problem. I think you want to change your transform stream into a writable, otherwise you have to do a ton of hackery like we had to do in vinyl-fs

Was this page helpful?
0 / 5 - 0 ratings