【问题标题】:Gulp stream inside a for loop not working properlyfor循环内的Gulp流无法正常工作
【发布时间】: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-promisebluebird 让它工作——见gist.github.com/rdallaire/e84a796a09e2aa189534

标签: javascript node.js gulp gulp-concat


【解决方案1】:

在 freenode irc 上 #gulpjs 人员的帮助下,它得以工作。

这使用stream-to-promisebluebird

var s2p = require('stream-to-promise');
var Promise = require('bluebird');

gulp.task('loop2', function() {
    // don't forget your `var`s!
    var buildIt = function(i){
        return gulp.src('./build/ross/templates/pages/_page_home.liquid')
            .pipe(plugins.insert.append('Loop ' + i))
            .pipe(gulp.dest('./build/ross/templates/pages/'))
            .on('end', function(){ console.log(i + ' -- done')});
    }

    var indexes = [];

    for(var i = 0; i < 10; i++) {
        indexes.push(i);
    }

    // // sequence them
    indexes.reduce(function(p, index){
        return p.then(function(){
            return s2p(buildIt(index));
        });
    }, Promise.resolve());

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    相关资源
    最近更新 更多