Nodejs - fs.createReadStream (). pipe, how to find out the size of a problem with a file

I am writing my own HTTP module if I need to respond with a binary file, for example ..jpg,

I load the file using: body = fs.createReadStream(pathOfFile) .

When I generate a response, I use: body.pipe(socket);

But as an HTTP response, I wanted to add a Content-Length header.

I could not find an easy way to do this, fs.stat does not give the result immediately, but right after I called the channel.

In any case, know what to send to the Content-Length header.

Thanks.

+4
source share
2 answers

Well, you should send a response and transfer the file after receiving the size using fs.stat, for example:

 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 }); 
+15
source

There is also a synchronous version (since you will block 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 
+1
source

Source: https://habr.com/ru/post/1387198/


All Articles