I am writing my own HTTP module, if I need to response with a binary file, e.g. .jpg,
I load the file using: body = fs.createReadStream(pathOfFile)
.
When I generate the response I use:body.pipe(socket);
But as its HTTP response, I had like to add a Content-Length
header.
I couldn't find an easy way to do it, fs.stat doesn't give the result immediately but just after I called pipe.
Anyway to know what to send in Content-Length
header. ?
Thanks.
Well you should only send the response and pipe the file after you get the size with fs.stat, like so:
fs.stat(file_path, function(error, stat) {
if (error) { throw error; }
response.writeHead(200, {
'Content-Type' : 'image/gif',
'Content-Length' : stat.size
});
// do your piping here
});
There is also a synchronous version (since you'll be blocking on file I/O anyway...) as mentioned in this other post
var stat = fs.statSync(pathOfFile);
response.writeHead(200, {
'Content-Type' : 'image/jpeg',
'Content-Length' : stat.size
});
// pipe contents
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