Questions And Answers

More Tutorials

NodeJS Sending a file stream to client

Using fs And pipe To Stream Static Files From The Server

A good VOD (Video On Demand) service should start with the basics. Lets say you have a directory on your server that is not publicly accessible, yet through some sort of portal or paywall you want to allow users to access your media.

var movie = path.resolve('./public/' + req.params.filename);
 fs.stat(movie, function (err, stats) {
 var range = req.headers.range;
 if (!range) {
 return res.sendStatus(416);
 //Chunk logic here
 var positions = range.replace(/bytes=/, "").split("-");
 var start = parseInt(positions[0], 10);
 var total = stats.size;
 var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
 var chunksize = (end - start) + 1;
 res.writeHead(206, {
 'Transfer-Encoding': 'chunked',
 "Content-Range": "bytes " + start + "-" + end + "/" + total,
 "Accept-Ranges": "bytes",
 "Content-Length": chunksize,
 "Content-Type": mime.lookup(req.params.filename)
 var stream = fs.createReadStream(movie, { start: start, end: end, autoClose: true })
 .on('end', function () {
 console.log('Stream Done');
 .on("error", function (err) {
 .pipe(res, { end: true });

The above snippet is a basic outline for how you would like to stream your video to a client. The chunk logic depends on a variety of factors, including network traffic and latency. It is important to balance chuck size vs. quantity.

Finally, the .pipe call lets node.js know to keep a connection open with the server and to send additional chunks as needed.


In this page (written and validated by ) you learned about NodeJS Sending a file stream to client . What's Next? If you are interested in completing NodeJS tutorial, your next topic will be learning about: NodeJS with Redis.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.