48

I am relatively new to gulp, and I was wondering what exactly does the .pipe() do in a gulp task? I've gathered that it usually runs after a return and after .src, but there must be more to it than that. I've been unable to find anything on the web or in gulp's documentation and I really want to understand what I'm using.

EDIT I found this, but it does a poor job of explaining it

Arlo
  • 963
  • 3
  • 11
  • 20
  • Gulp.js makes use of pipes for streaming data that needs to be processed. Its syntax for setting up tasks to me is extremely simple. If you haven't grasped the concept of how to use Gulp, then the API doc is not to read, it's just ment to reference developer to a certain method and how you use it. – Leroy Thompson Jul 15 '16 at 20:56
  • I have an image that Gulp .pipe() function is actually a promise. Is it? – Abdillah Sep 19 '16 at 15:14
  • @Abdillah no, `.pipe(destination)` returns the `destination`, which is a `Writable` stream. I was curious if Gulp attaches `.then`, `.catch`, and `.finally` methods to the `Writable` stream so that it can be used like a promise, but it doesn't as far as I can tell from the docs. – Andy Apr 21 '21 at 15:43

1 Answers1

46

From the Node docs:

https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options

The readable.pipe() method attaches a Writable stream to the readable, causing it to switch automatically into flowing mode and push all of its data to the attached Writable. The flow of data will be automatically managed so that the destination Writable stream is not overwhelmed by a faster Readable stream.

So in Gulp you can chain multiple tasks together using the pipe() method. Gulp makes use of streams. There are readable and writeable streams. Take the following snippet for example:

gulp.src(config.jsSrc)
    .pipe(uglify())
    .pipe(gulp.dest(config.dest + '/js'))
    .pipe(size());

gulp.src(...) turns the path at config.jsSrc into a readable stream of data that we are then piping to the gulp-uglify module. The uglify task returns a stream that we then pipe to our destination and so on...

Since a stream is usually a single file, some may be confused how Gulp is putting multiple files in the stream. Gulp actually uses streams in object mode:

gulp.src('*.js') reads all files ending in .js and emits each as an object on the stream.

Source: https://medium.com/gulpjs/gulp-sips-how-we-use-streams-d7790b22bf1a

Andy
  • 7,885
  • 5
  • 55
  • 61
pizzarob
  • 11,711
  • 6
  • 48
  • 69