我如何保证在我的应用程序中一次性使用 gulp?

2022-01-12 00:00:00 node.js javascript gulp q

作为我正在编写的一个小程序的一部分,我想使用 gulp 将大量文件转换为 markdown.这不是独立于程序的构建步骤的一部分.这是程序的一部分.所以我没有使用 gulpfile 来处理这个问题.

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.

问题是,因为它是异步的,所以我想使用一个 Promise,它会在 gulp 任务完成时提醒我.

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

这样的东西是理想的:

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;
}

pipe 不接受回调.我怎么能处理这个?感谢您的帮助,我对 gulp 有点陌生.

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

推荐答案

gulp 中的一切都是一个流,所以你可以只监听 enderror 事件.

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;
}

顺便说一句,Q 1.0 不再被开发(除了一些修复)并且将完全不兼容Q 2.0;我推荐 Bluebird 作为替代方案.

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.

还值得一提的是,NodeJS 0.12 及更高版本已内置 ES6 承诺(不需要 --harmony 标志),因此如果您不寻求向后兼容性,您可以使用它们来代替..

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);
  });
};

相关文章