Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs - fs.createReadStream().pipe, how to know size of file issue

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.

like image 511
user1066986 Avatar asked Dec 20 '11 13:12

user1066986


Video Answer


2 Answers

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
}); 
like image 87
alessioalex Avatar answered Oct 22 '22 01:10

alessioalex


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
like image 21
Spike0xff Avatar answered Oct 22 '22 01:10

Spike0xff