2014-06-09 84 views
0

我正在編寫一個gulp插件,它按照每個文件中的註釋註釋順序對流中的文件進行排序。我成功地對它進行了排序,但我不知道(因爲也許我不太瞭解流),如何將有序流返回給吞吐管道。如何在gulp插件中對文件進行排序

現在,我有這個,它的工作原理。

var through = require('through2'); 

module.exports = function (options) {   
    var graph = [], 
     files = {}; 

    var orderedStream = through.obj(); 

    var sortingStream = through.obj(function (file, enc, cb) { 
     //file.isNull() and file.isStream() code [...] 

     //get dependencies [...] 
     //graph.push(file with dependencies) [...] 

     files[file.path] = file; 

     cb(); 
    }, function (cb) { 
     var ordered = toposort(graph).reverse(); 

     async.eachSeries(ordered, function (filePath, callback) { 
      orderedStream.write(files[filePath], callback); 
     }, function() { 
      cb(); 
     }); 
    }); 

    return { 
     findOrder : function() { 
      return sortingStream; 
     }, 
     sortFiles : function() { 
      return orderedStream; 
     } 
    } 
}; 

這種方法的使用並不像我想要的那麼直截了當。你必須使用這樣的(它的工作原理):

gulp.task('default', function() { 
    var scripts = myPlugin(); 

    return gulp.src('src/**/*js') 
     .pipe(scripts.findOrder()) 
     .pipe(scripts.sortFiles()) 
     .pipe(concat('build.js')) 
     .pipe(gulp.dest('dist')); 
}); 

我希望有一個解決方案,它允許使用我的插件如下:

gulp.task('default', function() {  
    return gulp.src('src/**/*js') 
     .pipe(myPlugin()) 
     .pipe(concat('build.js')) 
     .pipe(gulp.dest('dist')); 
}); 

我嘗試了很多,但我做不到拿出任何工作解決方案。任何幫助表示讚賞。謝謝。

回答

0

當您必須首先檢查所有流時,請在返回之前對其進行處理,然後使用flush函數來提供流。

下面是一個例子:

var through = require('through2'); 
var files = []; 

through.obj(function (chunk, enc, cb) { 
    //store chunk in the files variable, do not push them onto the stream with this.push 
    files.push(chunk); 
    cb(); 
}, function (cb) { 
    //here is the flush function, files is now correctly provided 
    files.sort(); // do what you want with the array 

    //now you can push whatever you want into the stream 
    this.push(files[0]); 
    cb(); 
}); 
相關問題