How can I promise-ify a one-off usage of gulp in m

2019-02-12 10:50发布

问题:

As part of a small program I'm writing, I would like to use gulp to convert a large set of a files to markdown. This is not part of a build step separate from the program. It's a part of the program. So I'm not using a gulpfile to handle this.

The problem is, since it's async, I want to use a promise which will alert me when the gulp task is finished.

Something like this would be ideal:

io.convertSrc = function() {
  var def = q.defer();

  gulp.src(src + '/*.md')
    .pipe(marked({}))
    .pipe(gulp.dest(dist), function() {
      def.resolve('We are done!');
    });

    return def.promise;
}

But pipe doesn't take a callback. How could I handle this? Thanks for your help, I'm somewhat new to gulp.

回答1:

Everything in gulp is a stream, so you can just listen for the end and error events.

io.convertSrc = function() {
  var def = q.defer();
  gulp.src(src + '/*.md')
    .pipe(marked({}))
    .pipe(gulp.dest(dist))
    .on('end', function() {
      def.resolve();
    })
    .on('error', def.reject);
  return def.promise;
}

As an aside, Q 1.0 is no longer developed (aside from a few fixes here and there) and will be wholly incompatible with Q 2.0; I'd recommend Bluebird as an alternative.

Also worth mentioning that NodeJS 0.12 onwards has ES6 promises built into it (no --harmony flag necessary) so if you're not looking for backwards compatibility you can just use them instead..

io.convertSrc = function() {
  return new Promise(function(resolve, reject) {
    gulp.src(src + '/*.md')
      .pipe(marked({}))
      .pipe(gulp.dest(dist))
      .on('end', resolve)
      .on('error', reject);
  });
};


回答2:

Since the Gulp task is a stream, you can listen for its events:

io.convertSrc = function() {
  var def = q.defer();

  var stream = gulp.src(src + '/*.md')
    .pipe(marked({}))
    .pipe(gulp.dest(dist));

  stream.on('end', function() {
    def.resolve();
  });

  stream.on('error', function(err) {
    def.reject(err);
  });

  return def.promise;
};