我在本地做一个最简单的gulp的demo
var gulp = require('gulp');
var less = require('gulp-less');
var autoprefix = require('gulp-autoprefixer');
gulp.task('css', function(){
gulp.src('assets/app.less')
.pipe(less())
.pipe(autoprefix('last 2 version', 'ie 8', 'ie 9'))
.pipe(gulp.dest('build/css'));
});
现在我想看看.pipe()是在哪儿定义的,我找到了3个index.js,分别是:
node_modules/gulp-less/node_modules/gulp-util/node_modules/multipipe/index.js
node_modules/gulp-less/node_modules/gulp-less/node_modules/multipipe/index.js
node_modules/gulp-less/node_modules/gulp-autoprefixer/node_modules/multipipe/index.js
比如第一个index.js里有如下定义:
function pipe(){
if (arguments.length == 1) return arguments[0];
var streams = slice.call(arguments);
var cb;
if ('function' == typeof streams[streams.length - 1]) {
cb = streams.splice(-1)[0];
}
...
...
return ret;
}
现在,我想试着加进去一个console.log(),来查看pipe()函数的内部状况,比如:
function pipe(){
console.log("Here!");
if (arguments.length == 1) return arguments[0];
var streams = slice.call(arguments);
...
}
然后运行 gulp css
结果控制台并没有如我所愿出现 Here!
不知道是哪里的问题呢?
gulp是基于nodejs stream的,关于pipe方法,你可以查看nodejs stream API: https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
你所查看的 multipipe 也是对nodejs stream的进一步封装,至于你的console.log为什么无法输出,最好还是debug下可以使用 https://github.com/node-inspector/node-inspector
回答楼主的标题
首先,gulp的源码里没有任何一部分是定义pipe的。
gulp的pipe方法是来自nodejs stream API的。
gulp本身是由一系列vinyl
模块组织起来的。
pipe方法到底是什么呢?
pipe
跟他字面意思一样只是一个管道
例如我有一堆文件
var s = gulp.src(["fileA","fileB","fileC"])
src
方法实际上是'vinyl-fs'
模块的方法,选择一系列文件并创建可读流(readableStream)。
返回的是由从这些文件而来的流(stream)
既然是Stream,自然少不了最常用的pipe的方法。s.pipe(fn)
pipe方法传入方法的是一个function,这个function作用无非是接受上一个流(stream)的结果,并返回一个处理后流的结果(返回值应该是一个stream对象)。
注意的是这个函数只是一个包装,并不是会直接操作文件的。
这里面的思想跟可以阅读参考资料
http://www.zhangxinxu.com/wordpress/2013/02/js-currying/
http://www.cnblogs.com/kunhu/p/3608109.html
例如这样构造一个Stream对象并且返回,然后再stream的方法里把把文件内容log出来
var stream = require('stream');
s.pipe(()=>{
var fileStream = new stream.Transform({objectMode: true});
fileStream._transform = function(file, unused, callback){
console.log(file.contents);//把传入的文件内容log出来
this.push(file);//注意的是这个file是也必须是vinyl对象
callback();
};
return fileStream;
})
管道与Stream
也就是说pipe本身只是定义了管道的组织情况,管道本身的具体结构(Stream对象)
,是需要开发者自己去设计的。
pipe方法只负责返回这个管道结构(Stream对象)
楼主想要窥探管道里的内容,就要创建一个Stream对象,在Stream对象接收结果的方法里把流里的内容log出来即可
Stream与File
注意的是gulp里的流的file
必须是vinyl
对象
var File = require("gulp-utils").File
//或者
var File = require("vinyl")
var myf = new File()
myf.contents = new Buffer("haha")