h bob
h bob

Reputation: 3780

How to tell Gulp when a task is finished?

I am trying to write a gulp plugin which will count the number of files in the stream. I used this as a starting point:

function count() {

  var count = 0;

  function countFiles(data) {
    count++;
    // added this as per official docs:
    this.queue(data);
  }

  function endStream() {
    console.log(count + " files processed");
    // not doing this as per original post, as it "ends" the gulp chain:
    //this.emit("end");
    // so doing this instead as per official docs:
    this.queue(null);
  }

  return through(countFiles, endStream);
}


module.exports = count;

And here is a sample task:

gulp.task("mytask", function () {
  gulp
    .src("...files...")
    .pipe(count());                // <--- here it is
    .pipe(changed("./some/path"))
    .pipe(uglify())
    .pipe(rename({ extname: ".min.js" }))
    .pipe(gulp.dest(./some/path))
    .pipe(count());                // <--- here it is again
});

It works perfectly, except that it does not begin/end as expected:

[14:39:12] Using gulpfile c:\foo\bar\baz\gulpfile.js
[14:39:12] Starting 'mytask'...
[14:39:12] Finished 'mytask' after 9.74 ms
9 files processed
5 files processed

That means that the thing is running asynchronously and finishes after the task is complete. The docs say that you must use a callback or return a stream. It seems to be doing just that.

How do I make this function behave? Is it because I'm using the through rather than the through2 plugin?

Upvotes: 1

Views: 2650

Answers (1)

OverZealous
OverZealous

Reputation: 39580

Put return before gulp in your task. You haven't provided any way for gulp to know when your stream is finished.

Upvotes: 3

Related Questions