在Node.js / Gulp中重用streampipe道/子pipe道

从stream / gulp / vinyl开始,并尝试清理/使用stream-combiner2干掉我的gulp文件。 到目前为止,它工作得很好,除了现在我需要在另一个pipe道(简化的psuedocode-ish)中运行一个子pipe道:

var logger = require("gulp-logger"), HTMLPrettify = require("gulp-html-prettify"), combiner = require("stream-combiner2"), through = require("through2"), tap = require("gulp-tap"), _ = require("lodash"); preprocessPipeline = function() { return combiner.obj(getFrontMatter(), processTemplates()); }; gulp.task("build", ["clean"], function() { return gulp.src("in/**/*.html") .pipe(preprocessPipeline()) .pipe(tap(function(file) { var data, dataSources; dataSources = getDataSources(file); data = {}; /* PAUSE MAIN PIPELINE HERE */ /* RUN THIS SUB PIPELINE BELOW */ gulp.src(dataSources) .pipe(preprocessPipeline()) .pipe(tap(function(file) { _.merge(data, file.data); })); file.data = data; /* RESUME MAIN PIPELINE */ })) .pipe(HTMLPrettify()) .pipe(gulp.dest("out")); }); 

正如你所看到的,在主“构build”pipe道内,我正在尝试为主pipe道中的每个乙烯基文件对象执行以下操作:

  • 暂停主“构build”pipe道的执行
  • 通过同步的getDataSources()函数获取当前乙烯文件的数据源path
  • 使用另一个子pipe道来处理这些数据源path,重新使用preProccessPipeline并最终合并它们的数据
  • 最后将来自数据源的合并数据添加到主pipe道中的乙烯基文件,并在主pipe道中继续执行

gulp.src()看起来像是将这些数据源文件加载到子pipe道中的完美方式,但gulp.src()道似乎在子pipe道启动之前完成。

另外,我开始意识到,也许我的pipe道看起来像同步functionstream程,很可能我错过了stream / node.js难题的关键部分。

相关的文档帮助我重新使用了pipe道,但是没有使用子pipe道:

  • https://github.com/gulpjs/gulp/blob/master/docs/recipes/sharing-streams-with-stream-factories.md
  • https://github.com/gulpjs/gulp/blob/master/docs/recipes/make-stream-from-buffer.md

相关问题:

  • 有没有什么方法可以在NodeJS中重复使用一系列pipe道转换?

谢谢。

好像你正在使用gulp作为模板引擎 – 完全可行。

Gulp允许你指定哪些任务依赖于其他任务,因此你可以将子pipe道分解为一个新的任务,比如说"buildDataFiles" ,然后让你的构build任务依赖于这个任务

 gulp.task("build", ["buildDataFiles", "clean"], function(){ 

但是,正如你所说的,这种方法的问题是“在处理模板之前,不可能知道与模板文件相关的数据文件”。 如果你确定没有办法解决这个问题,那就更棘手了。 如果相反,如果将"processTemplate"分解为"processTemplate"任务,那么"build"任务只处理子pipe道,但是依赖于"processTemplate" ? 它可能看起来像这样:

 gulp.task("processTemplate", ["clean"], function() { gulp.src("in/**/*.html") .pipe(preprocessPipeline()) .pipe(gulp.dest("build/temp")); } gulp.task("build", ["processTemplate"], function() { gulp.src("build/temp/*.html") .pipe(tap(function(file) { var data, dataSources; dataSources = getDataSources(file); data = {}; gulp.src(dataSources) .pipe(preprocessPipeline()) .pipe(tap(function(file) { _.merge(data, file.data); })); file.data = data; })) .pipe(HTMLPrettify()) .pipe(gulp.dest("out")); } 

它看起来非常相似,但是遇到的问题要求首先处理模板,然后处理数据文件。 我会试着检查一下吞咽巩固 ,它可能会帮助你。