Search code examples
node.jsmu

Nodejs - Piping MU2 to HTTP?


Mu (Node.js Mustache engine) documents a method of using util.pump() to read its stream into the HTTP write stream. But util.pump() has been deprecated in favor of the pipe() method on the stream object.

So my test for doing this is:

var http = require('http');
var mu = require('mu2');

http.createServer(function(req, res) {
    mu.compileText("testname", "Hello world");
    var stream = mu.render("testname", {});
    stream.pipe(res);
    res.end();
}).listen(8888);

But it doesn't output anything. I also tried util.pump() and this didn't work either.

I am, however, able to attach an on-data event to mu::render() and write the data to the res this way.

What am I doing wrong when piping the the MU stream to HTTP?

I'm using node version 0.10.5 and [email protected].


Solution

  • The solution is to check for the MU steam end event before ending the HTTP response stream:

    var http = require('http');
    var mu = require('mu2');
    
    http.createServer(function(req, res) {
        mu.compileText("testname", "Hello world");
        var stream = mu.render("testname", {});
        stream.pipe(res);
    
        // Here's the trick.
        stream.on('end', function() {
            res.end();
        });
    }).listen(8888);