Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

createReadStream send file http

I'm trying to open an img file and send it through http. I have read that the best method for doing it is creatReadStream because it's async and better for performance.

Here it's my code:

var file = fs.createReadStream(image);

    file.on("error", function(err){
        ...
    });

    res.writeHead(200, {"Content-Type" : "image/png"});

    file.on("data", function(data) {
        res.write(data);
    })

    file.on("end", function() {
        res.end();
    })

How can I know the file size to let res know in order to send it in the headers?

I don't like having writehead not in a callback, what can I do?

Thank you.

like image 905
Mario Avatar asked Dec 12 '22 20:12

Mario


2 Answers

var stat = fs.statSync('path/to/imagefile');
response.writeHead(200, {
  'Content-Type' : 'image/png',
  'Content-Length': stat.size
});
fs.createReadStream('path/to/imagefile').pipe(response);
like image 189
wayne Avatar answered Jan 08 '23 17:01

wayne


The res.writeHead() call is in the right place but the event listeners could be replaced with file.pipe(res); as you are only forwarding the data from the read stream to the write stream of the res. Also the HTTP response code 202 doesn't seem appropriate why not use 200.

var file = fs.createReadStream(image);
res.writeHead(200, {"Content-Type" : "image/png"});
file.pipe(res);
like image 36
Dan D. Avatar answered Jan 08 '23 17:01

Dan D.