How to stream a .m4v video with NodeJS

3.5k Views Asked by At

What I need is to be able to send videos that are on the server local files to the client. I can't create a static 'videos' folder as these videos will only be temporarily available, meaning i'll have dynamic videos.

So how can I retrieve the playable .m4v video file from the server files (if i know the path) and send it to the angular.io client to play

2

There are 2 best solutions below

0
On

Here is a simple solution:

On server side:

app.get('/video', function(req, res) {
  const path = 'assets/sample.m4v'
  const stat = fs.statSync(path)
  const fileSize = stat.size
  const head = {
    'Content-Length': fileSize,
    'Content-Type': 'video/mp4',
  }
  res.writeHead(200, head)
  fs.createReadStream(path).pipe(res)
})

On client side (html):

<video id="videoPlayer" controls>
  <source src="http://localhost:3000/video" type="video/mp4">
</video>

Maybe you should set different media type like video/x-m4v instead of video/mp4.

Source link

2
On

This was enough with me. MP4 has native support for strimming (pseudo streaming). It worked very well for watching videos in the browser via streaming.

const router    = require('express').Router();
...
router.get('/video/:acckey', async (req, res, next)=>{
  ...
  let full_path = await myAccessControl.auth(acckey);
  ...
  if (fs.existsSync(full_path)) {
    res.setHeader('Content-Type', 'video/mp4');
    res.status(200).sendFile(full_path, function (err) {
      if (err) {...} else {...}
    });    
  }    
}

In HTML (reduced):

<VIDEO controls src="domain.com/video/PSMAPKMDPAMDPSMPSD/">