Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

javascript - How can I write a simple gulp pipe function?

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 outputCSS for each file in the second pipe. How can I send it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, you don't need to use fs here, you already got the stream of file (here your 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.

const through = require('through2')

gulp.src(sources)
  .pipe(through.obj((chunk, enc, cb) => {
    console.log('chunk', chunk.path) // this should log now
    cb(null, chunk)
  }))

In 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((file, enc, cb) => {
  less.render(file.contents, { filename: file.path, ... }) // add other options
    .then((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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...