Javascript 如何编写一个简单的 gulp 管道函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27923523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:54:41  来源:igfitidea点击:

How can I write a simple gulp pipe function?

javascriptnode.jsgulp

提问by Vlad Nicula

I've been trying for a day to write two pipe functions, one that compiles less files and another one that concats these files. I want to learn how to write transform streams/pipes for more complex plugins.

我已经尝试了一天来编写两个管道函数,一个编译较少的文件,另一个连接这些文件。我想学习如何为更复杂的插件编写转换流/管道。

So I want to know how to read data from another pipe, and how to alter that data and send it to the next pipe. This is what I have so far:

所以我想知道如何从另一个管道读取数据,以及如何更改该数据并将其发送到下一个管道。这是我到目前为止:

 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();
   }))

I can't get the outputCSSfor each file in the second pipe. How can I send it?

我无法获取outputCSS第二个管道中的每个文件。我该如何发送?

回答by Balthazar

Well, you don't need to use fshere, you already got the stream of file (here your chunk).

好吧,您不需要在fs这里使用,您已经获得了文件流(这里是您的chunk)。

Another point, you're not sending back to the pipe the files, so I guess that's why nothing is called on your second one.

另一点,您没有将文件发送回管道,所以我想这就是为什么您的第二个文件没有被调用的原因。

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)
  }))

In ES2015:

在 ES2015 中:

import through from 'through2'

gulp.src(sources)
  .pipe(through.obj((chunk, enc, cb) => cb(null, chunk)))

And for your specific example:

对于您的具体示例:

.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)
    })
}))

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.

这仍然是非常基本的,我不检查错误,如果它不是流等等,但这应该会给你一些关于你错过了什么的提示。