Library of The Month: merge2

First a bit of administrivia: we've decided to move to a monthly pace for our periodic looks at interesting JavaScript libraries, so from now on this series will be entitled... wait for it... "Library of the Month".

With that in mind, let's take a closer look this month at the Gulp world. Those familiar with Gulp's predecessor Grunt have probably already heard about two important differences between these tools. First, Gulp uses normal JavaScript code instead of declarative configuration. Second, Gulp uses streams and pipes instead of writing intermediate results to the file system.

When starting out with Gulp, you will probably be impressed by how easily you can write basic tasks using simple pipelines. Complications arise, however, once you need to manage own streams (e.g. by combining them). Gulp itself doesn't help you much with this, since it provides only a minimal framework and leaves the rest for external libraries to handle. This makes sense because it uses standard Node.js streams with their own API and ecosystem. This leads us to this month's library: merge2.

merge2 builds on the substantial success of merge1*. It is small utility that can merge multiple streams into one, in sequence or in parallel. In the following example, we have one stream containing a bunch of JPEG images that we have resized, and the other containing a text file. They are written together into a single ZIP file:

gulp.task('thumbs', function() {  
    return merge2(
      gulp.src(['**/*.jpeg'])
        .pipe(imageResize({
           width: 320,
           height: 200
        })),
      gulp.src(['manifest.txt'])
    )
    .pipe(zip('thumbs.zip'))
    .pipe(gulp.dest('outdir'));
});

There are a lot of situations that can be addressed using multiple Gulp tasks and combining partial results (as with Grunt). For instance, if you want to deploy a web application, you needs to uglify JavaScript files and compile SASS files into CSS. In this case, it doesn't make sense to combine streams because you need the files you produce to reside in the file system anyway. But in many other cases, partial results are unnecessary and merge2 is a better choice.

*Kidding!

Roman Krejčík

Roman Krejčík