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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With