【发布时间】:2015-05-05 19:18:35
【问题描述】:
我有一个类似于以下内容的 gulp 任务。我正在尝试循环并将字符串附加到页面,并连接相应的文件。
gulp.task('loop', function() {
for(i =0; i < 10; i++) {
gulp.src('./build/ross/templates/pages/_page_home.liquid')
.pipe(plugins.insert.append('Loop ' + i))
// real example has concat here
.pipe(plugins.addSrc('./src/page/_page' + i + '.liquid'))
.pipe(plugins.concat('_page_home.liquid'))
.pipe(gulp.dest('./build/ross/templates/pages/'));
}
});
预期的输出会是这样的
Loop 1
// _page1.liquid contents
Loop 2
// _page2.liquid contents
Loop 3
// _page3.liquid contents
and so on...
实际输出看起来更像
// Original Page Contents here
Loop 9
// _page9.liquid contents
我在循环中对原始文件执行了fs.readFile 并输出了数据,它只输出原始页面内容,而不是连接文件或我要附加的字符串。
我还在里面做了一个console.log(i),它显示了正确的数字1,2,3,4,5,6,7,8,9。我想知道这是否与 gulp.src() 有关
更新:有时看起来输出内容实际上会包含 _page#.liquid 内容的一部分。这有点不一致。
有没有更好的方法来用 gulp 做到这一点,还是我只是做错了什么?
【问题讨论】:
-
如果我
console.log(i)它将输出 0,1,2,3,4,5,6,7,8,9 等... -
在你的 gulp-pipes 中你是异步的!您的循环本身不是异步的。将循环中的内容放在一个函数中,然后从循环中调用它(使用
i作为参数),你会看到它会起作用! -
我仍然遇到同样的问题,我怎样才能告诉一个流在做其他事情之前完成?
-
使用
stream-to-promise和bluebird让它工作——见gist.github.com/rdallaire/e84a796a09e2aa189534
标签: javascript node.js gulp gulp-concat