Using fs And pipe To Stream Static Files From The Server

suggest change

A video-on-demand handler can read a file that is not served as a public directory. path, fs, and mime are required by the handler below and are not imported in this fragment. req and res are the HTTP request and response.

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) {

                    res.end(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 chunk size. A missing Range header is a normal full-file request. Status 416 means the range cannot be satisfied, but this handler sends 416 whenever Range is absent. If fs.stat fails, stats is undefined and stats.size throws. Content-Length and Transfer-Encoding: chunked contradict each other. mime.lookup is the mime package v1 call. pipe writes this range to the response and then ends it. It does not later decide to send more of the file.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents