codeKiller
codeKiller

Reputation: 5739

Serving video with Node.js

I am writing a simple Node.js server to serve videos from my laptop into my local network.

I have been searching around, to check the best way, and I found two ways of doing it, I would like some help figuring out if there is one way that is preferred over the other when it comes to serve video files using nodejs.

Video files would be huge video files, movie size....

Option 1: using Express:

I have seen some people that, after creating all the usual boilerplate code for an Express server, when it comes to sending the video, they would just do something like:

app.get('/getMovie', (req, res) => {
    res.sendFile('assets/video.mp4', { root: __dirname });
});

Option 2: using Http:

For this option, after creating the http server and so on, people would create first a ReadStream using fsand then send the video. Something like:

res.writeHead(200, {'Content-Type': 'video/mp4'});
let readStream = fs.createReadStream("movie.mp4");
readStream.pipe(res);

For me, option 2 sounds more reasonable when it comes to huge video files, but, not sure which one would be best and why.

Upvotes: 1

Views: 3793

Answers (1)

Mick
Mick

Reputation: 25471

Express server-static will accept range requests so it does not actually serve the entire video file in one go.

Range requests allow the client to request the video in chunks. So long as the headers are at the start of the video this allows the client to start playing the video as it downloads it.

The network messaging below from a browser inspection, safari in this case, shows an example of a request to a server for a video that accepts range requests:

enter image description here

You can see the response include information that informs the client, a browser in this case, that the server accepts range requests.

If you look at the following request in the left of the image you can see that it requests the video chunk by chunk from a start to an end byte. For example here is a request and response for bytes 81920 to 98303:

enter image description here

You can see more about Express serve-static here: http://expressjs.com/en/resources/middleware/serve-static.html

Upvotes: 2

Related Questions