Get method gets called n number of times when streaming MEAN stack

39 Views Asked by At

I have a MEAN stack, when the frontend calls for a url like /movies/KN3MJQR.mp4,

the get block in the routes.js looks like this

app.get('/movie/:url', function(req, res) {
        try {
            var url = req.url.split('/')[2]
                res.sendfile(moviesFolder + url);
         #i want to add my logic for incrementing view count here. 

        } catch (e) {
            console.log(e);
        }
    });

I want to add logic to increment the view count of each of the movie whenever a request is raised for the .mp4 . I tried adding the increment view count logic at the place commented in the code as shown above only to find that the whole get method gets called n number of times as the streaming happens. How do I handle this logic?

Update : Code to check the same as answered by @rsp

if(req.get('Range')===('bytes=0-')){
     console.log('first call');
}else{
     console.log('further call');
}
1

There are 1 best solutions below

0
On BEST ANSWER

The endpoint can be hit many times because res.sendfile() supports ranges and the client can do multiple downloads of partial data.

You can inspect the relevant header with req.get('Range') and see if it's the first or last part (depending on whether you want to count every started download or only the finished ones).

For more info on the header, see: