0

I have an issue with outputting the readable stream to the http response.

behind the scenes there is a regular request and response streams coming from the generic http createServer. I check to see if the 'req.url' ends in css, and I create a readable stream of this file. I see the css contents in the console.log, with the right css code I expect. Then, I try to pipe the readable css file stream to the response, but in Chrome, the file response is blank when I inspect the response. It is a 200 response though. Any thoughts at first glance? I've tried different variations of where I have code commented out.

router.addRoute("[a-aA-z0-9]{1,50}.css$", function(matches){
    var cssFile = matches[0];
    var pathToCss = process.cwd() + "/" +  cssFile;
    // takes care of os diffs regarding path delimiters and such
    pathToCss = path.normalize(pathToCss);
    console.log(matches);
    console.log("PATH TO CSS");
    console.log(pathToCss)
    var readable = fs.createReadStream(pathToCss);

    var write = function(chunk){
        this.queue(chunk.toString());
        console.log(chunk.toString());
    }
    var end = function(){
        this.queue(null);
    }
    var thru = through(write,end);
    //req.on("end",function(){
        res.pipe(readable.pipe(thru)).pipe(res);
        //res.end();
    //});


});
med116
  • 1,526
  • 17
  • 16

2 Answers2

1

you need to pipe your readable stream into your through-stream, and then pipe it into the response:

readable.pipe(thru).pipe(res);

edit: for preparing your css path, just use path.join instead of concatenating your path and normalizing it:

var pathToCss = path.join(process.cwd(), cssFile);
hereandnow78
  • 14,094
  • 8
  • 42
  • 48
  • Thanks for the help, I used `var pathToCss = path.basename(cssFile);` instead of joining the path, afterall, I was after the filename itself, not the path leading up to it. – med116 May 04 '14 at 19:14
0

I separated out this route (css) from my normal html producing routes, the problem I had was that my normal routes in my router object returned strings, like res.end(compiled_html_str), and the css file readable stream was going through that same routing function. I made it separate by isolating it from my router.

var cssMatch = [];

if(cssMatch = req.url.match(/.+\/(.+\.css$)/)){

    res.writeHead({"Content-Type":"text/css"});

    var cssFile = cssMatch[1];

    var pathToCss = process.cwd() + "/" +  cssFile;

    // takes care of os diffs regarding path delimiters and such

    pathToCss = path.normalize(pathToCss);

    console.log(cssMatch);

    console.log("PATH TO CSS");

    console.log(pathToCss)

    var readable = fs.createReadStream(pathToCss);

    var cssStr = "";

    readable.on("data",function(chunk){

        cssStr += chunk.toString();

    });

    readable.on("end",function(){

        res.end(cssStr);

    });

}
med116
  • 1,526
  • 17
  • 16