Vla*_*ula 52 javascript node.js gulp
我一直在尝试编写两个管道函数,一个编译较少的文件,另一个编译这些文件.我想学习如何为更复杂的插件编写转换流/管道.
所以我想知道如何从另一个管道读取数据,以及如何更改该数据并将其发送到下一个管道.这是我到目前为止:
gulp.src(sources)
.pipe(through.obj(function (chunk, enc, cb) {
var t = this;
// console.log("chunk", chunk.path);
fs.readFile(chunk.path, enc, function (err,data) {
if (err) { cb(err); }
less.render(data, {
filename : chunk.path,
sourceMap : {
sourceMapRootpath : true
}
})
.then(function (outputCss) {
// console.log("less result",outputCss);
t.push(chunk);// or this.push(outputCss) same result
cb();
});
});
}))
.pipe(through.obj(function (chunk, enc, cb) {
console.log("chunk", chunk.path); // not event getting called.
cb();
}))
Run Code Online (Sandbox Code Playgroud)
我无法获取outputCSS
第二个管道中的每个文件.我该怎么发送?
Bal*_*zar 60
好吧,你不需要在fs
这里使用,你已经得到了文件流(这里是你的chunk
).
另一点,你不是要把文件送回管道,所以我猜这就是为什么你的第二个没有调用任何东西.
var through = require('through2')
gulp.src(sources)
.pipe(through.obj(function (chunk, enc, cb) {
console.log('chunk', chunk.path) // this should log now
cb(null, chunk)
}))
Run Code Online (Sandbox Code Playgroud)
在ES2015中:
import through from 'through2'
gulp.src(sources)
.pipe(through.obj((chunk, enc, cb) => cb(null, chunk)))
Run Code Online (Sandbox Code Playgroud)
而对于您的具体示例:
.pipe(through.obj(function (file, enc, cb) {
less.render(file.contents, { filename: file.path, ... }) // add other options
.then(function (res) {
file.contents = new Buffer(res.css)
cb(null, file)
})
}))
Run Code Online (Sandbox Code Playgroud)
This is still pretty basic, I don't check for errors, if it's not a stream and so on, but this should give you some hint on what you've missed.