若效果不佳,参阅https://www.zybuluo.com/bornkiller/note/32907。javascript
前端开发近两年工程化大幅飙升。随着Nodejs
大放异彩,静态文件处理再也不须要其余语言辅助。主要的两大工具即为基于文件的grunt
,基于流的gulp
。简单来讲,若是须要的只是文件处理,gulp
绝对首选。若是是其余依赖于文件的任务管理,例如测试(karma
,mocha
),推荐使用grunt
。前端
就插件开发难度而言,gulp远低于grunt。若是你只关注如何处理文件,而不关注细节,那么须要依赖Nodejs Transform stream
的实现。可使用官方推荐的through2
,但推荐使用through-gulp
。后者是基于前者,为gulp插件编写精简优化重写而来。千万不要使用through
,这个包时间久远,长时间没有维护,并且部分mock实现的功能,到nodejs 0.10.x
已经原生支持。若是只是想学习如何编写gulp插件,through-gulp
更适合。through-gulp
: https://github.com/bornkiller/through-gulpthrough2
: https://github.com/rvagg/through2.gitthrough
: https://github.com/dominictarr/throughjava
// PLUGIN_NAME: sample var through = require('through-gulp'); function sample() { // creating a stream through which each file will pass var stream = through(function(file, encoding,callback) { // do whatever necessary to process the file if (file.isNull()) { } if (file.isBuffer()) { } if (file.isStream()) { } // just pipe data next, or just do nothing to process file later in flushFunction // never forget callback to indicate that the file has been processed. this.push(file); callback(); },function(callback) { // just pipe data next, just callback to indicate that the stream's over this.push(something); callback(); }); // returning the file stream return stream; }; // exporting the plugin module.exports = sample;
then use the plugin with gulpnode
var gulp = require('gulp'); var sample = require('sample'); gulp.task('sample', function() { return gulp.src(['source file']) .pipe(sample()) .pipe(gulp.dest('file destiny')) });
这个sample
是一个plugin的基本模板,一般关注的重点在于此处。git
if (file.isBuffer()) { //文件处理 }
须要特别注意的是,若是你须要处理的不一样文件之间没有任何依赖,在第一个函数函数内部处理完后,进行以下调用,便可将该文件的处理结果传递给下一个插件。这种状况下,能够缺省第二个参数flushFunction
。github
if (file.isBuffer()) { // 文件处理 var data = fileProcess(file); // 传递处理后数据给下一个插件 this.push(data); // 声明该文件处理完毕 callback(); }
若是须要处理的不一样文件之间存在依赖,例如文件合并,须要全部文件所有读完以后再处理,那么第一个参数transformFunction
将每次传递进来的数据保存在内存中(绝对不要在这里调用this.push()
方法),第二个参数flushFunction
统一作处理后,再传递给下一个插件。gulp
// transformFunction var fileStorage = []; if (file.isBuffer()) { // 文件处理 var data = fileProcess(file); // 保存传递进来的数据 fileStorage.push(data); // 声明该文件处理完毕 callback(); }
// flushFunction function(callback) { var result = ''; var final = null; fileStorage.foreach(function(file, key) { result += file.contents.toString(); }) final = new Buffer(result); this.push(final); callback(); }
就插件编写的角度而言,through-gulp
能够把你从through2
晦涩的文档中解救出来,不过有一个不幸的地方,在插件开发的单元测试中,经常使用的assert-stream
是基于through2
的,可是不影响大局。近期考虑本身从新实现一个版本,基于through-gulp
,目的在于为gulp插件编写下降难度。同时through-gulp
目前彻底可用,欢迎改造。https://github.com/bornkiller/through-gulp。dom