Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs stream vs sendFile

I am testing on download speed both res.sendFile(src); and fs.createReadStream(src).pipe(res); and i don't see much difference. Which is better to serve files and why? If i will have huge files, stream will handle it better?

like image 598
Honchar Denys Avatar asked May 23 '16 20:05

Honchar Denys


People also ask

What is Node.js stream?

What are Streams? Streams are objects that let you read data from a source or write data to a destination in continuous fashion. In Node.js, there are four types of streams − Readable − Stream which is used for read operation. Writable − Stream which is used for write operation.

Why Node.js is stream based?

Streams are one of the fundamental concepts of Node. js. Streams are a type of data-handling methods and are used to read or write input into output sequentially. Streams are used to handle reading/writing files or exchanging information in an efficient way.

What does sendFile return?

res.sendFile(path [, options] [, fn]) Parameter: The path parameter describes the path and the options parameter contains various properties like maxAge, root, etc and fn is the callback function. Returns: It returns an Object.


1 Answers

I would opt for using res.sendFile().

Ultimately, res.sendFile() pipes a stream to res, so in that regard they are basically the same.

However, res.sendFile() does some extra stuff, like setting the proper HTTP Content-Type header based on the filename, and because it uses the send library under the hood it can (probably, I haven't tested this) handle partial responses and do content negotiation.

like image 200
robertklep Avatar answered Oct 04 '22 23:10

robertklep