2014-10-05 26 views
3

考慮這兩個一飲而盡任務:爲什麼一些Gulp流默認爲「流動」,而另一些則不?

gulp.task('src', function(done) { 
    gulp.src('docs/*') 
    .on('end', function() { 
     console.log('ending'); 
     done(); 
    }); 
}); 

gulp.task('dest', function(done) { 
    gulp.src('docs/*') 
    .pipe(gulp.dest('temp')) 
    .on('end', function() { 
     console.log('ending'); 
     done(); 
    }); 
}); 

運行gulp dest行爲與預期相同,輸出:

[12:33:15] Using gulpfile ~/Projects/gulp-exit/gulpfile.js 
[12:33:15] Starting 'dest'... 
ending 
[12:33:15] Finished 'dest' after 13 ms 

但是,運行gulp src只輸出:

[12:31:11] Using gulpfile gulpfile.js 
[12:31:11] Starting 'src'... 

'end'回調不會被調用。經過一些調試,我認爲dest任務中的流是flowing,而源任務中的流不是。

信令的src任務通過調用stream.resume()明確流向:

gulp.task('src', function(done) { 
    gulp.src('docs/*') 
    .on('end', function() { 
     console.log('ending'); 
     done(); 
    }) 
    .resume(); 
}); 

給人的預期輸出:

[12:46:52] Using gulpfile gulpfile.js 
[12:46:52] Starting 'src'... 
ending 
[12:46:52] Finished 'src' after 11 ms 

我已經看到了這個同樣的行爲的混合使用插件:gulp.destgulp-mocha似乎返回流動的流,而gulp-loggergulp-gh-pages不。

爲什麼行爲上的差異?

回答

2

不是一個答案,爲什麼,但我扔在一起stream-end模塊,以平滑短期內怪癖:

end = require('stream-end') 

gulp.task 'logger', (done) -> 
    gulp.src 'docs/*' 
    .pipe logger() 
    .pipe end -> 
     console.log('ending') 
     done() 

傳遞給最終的回調被稱爲上游是否流與否。

2

發生這種情況的原因是因爲某些流有數據需要讀取,有些則不需要。

gulp.src('docs/*')返回一個可讀流,其中包含docs中每個文件的數據。一旦從流中讀取所有數據,end事件僅觸發可讀流。

通常你管這這這是否自動,但因爲你不是,你將需要使用另一個流:

gulp.task('src', function(done) { 
    gulp.src('docs/*') 
    .on('data', function() {}) 
    .on('end', function() { 
     console.log('ending'); 
     done(); 
    }); 
}); 

或者您可以使用finish事件,(我認爲)等待直到所有數據已被推到流(即它的完成工作):

gulp.task('src', function(done) { 
    gulp.src('docs/*') 
    .on('finish', function() { 
     console.log('ending'); 
     done(); 
    }); 
}); 

你的第二個一飲而盡任務使用gulp.dest('temp')返回沒有數據流,所以end就被觸發的STR eam正在完成處理。

相關問題