Gulp任务:循环内部stream

关键是读取someFolder所有文件,然后用someFolder gulp-inject-string 使用这个问题的不相关标准将它们注入到一个固定的文件中。

我有一些伪代码:

 var gulp = require('gulp'); var inject = require('gulp-inject-string'); var fs = require("fs"); gulp.task('compile', function() { /* reading the file names in the directory */ var fileNames = fs.readdirSync('someFolder', 'utf8'); fileNames.forEach(function(fileName) { /* getting the whole file content and then removing what I don't want to be injected with a regex */ var wholeFile = fs.readFileSync('someFolder/' + fileName, 'utf8'); var file = wholeFile.replace(/<!-- COMMENT-WITH-SOME-FIXED-STRING:. * -->[\r\n]/g, ''); /* now getting into mainFile to inject this file */ gulp.src('mainFolder/mainFile.html') /* injecting the content after it has been processed by the regex exactly where I need it (which depends on the fileName I got earlier) */ .pipe(inject.afterEach('<!-- COMMENT-WITH-SOME-FIXED-STRING+FILENAME: ' + fileName + ' -->', file)) .pipe(gulp.dest('mainFolder')); }); }); 

这个工作正常,如果我只有一个文件someFolder ,否则它只注入最后一个读取文件。

我试图把这个stream吸收到一个普通的for循环中的一个匿名函数,像下面这样:

for(var i...){ (function(i){ /* stream stuff here*/ })(i) }我已经做了几次与JavaScript的asynchronous操作,但有完全相同的结果。

我也尝试使用merge-stream映射函数over fileNames返回stream本身,然后应用合并,但同样的结果。

试图处理这些stream的时候,我做错了什么?

这是有用的东西:

 var gulp = require('gulp'); var inject = require('gulp-inject-string'); var fs = require("fs"); gulp.task('compile', function() { /* reading the file names in the directory */ var fileNames = fs.readdirSync('someFolder', 'utf8'); var stream = gulp.src('mainFolder/mainFile.html'); fileNames.forEach(function(fileName) { var file = fs.readFileSync('someFolder/' + fileName, 'utf8'); stream = stream.pipe(inject.afterEach('<!-- include: ' + fileName + ' -->', file)); }); return stream.pipe(gulp.dest('destFolder')); }); 

我还没有在mainFolder/mainFile.html上进行文本replace,因为它不是什么导致你的失败,而且是微不足道的添加。 我也将输出发送到一个不同的文件夹( destFolder ),因为我绝对讨厌gulpfiles修改他们的input。 这使得debugging这样的gulp文件非常困难。

关键是:

  1. 你需要把一些东西还给Gulp,以便知道你的任务何时结束。 否则, 可能会在任务结束之前终止。

  2. 您必须返回链接stream中所有操作的结果。

  3. 通常可以在一个stream中使用多个gulp.dest ,但在这种情况下,只能使用一个gulp.dest ,否则只会得到部分结果。

给出以下input。

 $ cat mainFolder/mainFile.html <!-- include: a --> Other stuff. <!-- include: b --> Other stuff. <!-- include: a --> Other stuff. <!-- include: b --> $ cat someFolder/a File a's contents. $ cat someFolder/b File b's contents. 

运行gulp compile产生:

 $ cat destFolder/mainFile.html <!-- include: a -->File a's contents. Other stuff. <!-- include: b -->File b's contents. Other stuff. <!-- include: a -->File a's contents. Other stuff. <!-- include: b -->File b's contents. 

你可以用gulp.src为你做,然后将每个文件注入到主文件中,而不是使用fs到目录和文件。

 gulp.src('someFolder/*.*') // or a specific file type .pipe(inject.afterEach('someCriteriaInTheMainFile', file)) .pipe(gulp.dest('mainFileFolderContainer'));