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?
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.
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.
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.
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.
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