Skip to content Skip to sidebar Skip to footer

Piping Concatenated Gulp Stream File.contents To Server (connect, Express Or Http) Response

I suspect this comes from a limited understanding of streams but I've looked everywhere and cannot get it to work. In short, I want to take a Gulp stream and pass the concatenated

Solution 1:

gulp works on streams of virtual File objects, not physical files. As such, gulp-concat doesn't write to the file system no matter what name you give it. However, you will still have a problem because you cannot send these file objects directly to the res response.

You need to write the contents of the virtual file(s) to res. An easy way to do this is to use through to make a stream that reads the gulp input and writes the files' contents to res. If your stream handles multiple files, then you don't need concat.

var through = require('through');

// create a stream that reads gulp File objects and outputs their contents
function sendTo(res) {   
    return through(
        function write(data) {    // this will be called once for each file
            res.write(data.contents);
        },
        function end() {    // this will be called when there are no more files
            res.end()
        }
    );
}

app.get('/app/js/concatenated-js-files.js', function(req, res){
    gulp.src('app/js/**/*.js')
        .pipe(sendTo(res));
});

Also, gulp internally uses vinyl-fs to read the files, so you can use vinyl-fs directly if have no other need for gulp.


Post a Comment for "Piping Concatenated Gulp Stream File.contents To Server (connect, Express Or Http) Response"