重点是读取 someFolder
中的所有文件,然后使用与此问题无关的标准使用 gulp-inject-string
将它们注入(inject)到固定文件中。
我所拥有的一些伪代码:
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
中只有 1 个文件,则此方法可以正常工作,否则它只会注入(inject)最后读取的文件。
我尝试将流吸收到公共(public) for 循环内的匿名函数中,执行以下操作:
for(var i...){ (function(i){/* 在这里传输内容*/})(i) }
正如我在 javascript 中使用异步操作做过几次一样但得到了完全相同的结果。
我还尝试使用 merge-stream
在 fileNames
上映射一个函数,该函数返回流本身,然后应用合并,但同样的结果。
在尝试处理流时我做错了什么?
最佳答案
这是有效的:
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
进行文本替换,因为它不是导致失败的原因,而且添加起来很简单。我还将输出发送到不同的文件夹 (destFolder
),因为我绝对讨厌就地修改输入的 gulpfiles。它使得调试这样的 gulpfiles 变得非常困难。
关键是:
您需要向 Gulp 返回一些内容,以便它知道您的任务何时结束。否则,它可能在任务结束之前终止。
您必须返回链接流上所有操作的结果。
单个流中通常可以有多个
gulp.dest
,但在这种情况下,您应该只使用一个gulp.dest
,否则,您只会得到部分结果。
给出以下输入。
$ 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.
运行gulpcompile
会产生:
$ 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.
关于javascript - Gulp任务: Streams inside loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37358157/