'Stream video from Gridfs mongoDB

I'm trying to stream video by chunks , video is stored in mongodb using grid fs ,

here is the API :

videoRoute.get('/:id', (req, res) => { 
GFS.findById(req.params.id, (err: any, file: any) => {
// Check if file
if (!file || file.length === 0) {
  return res.status(404).json({
    err: 'No file exists',
  });
}
// Read output to browser

const range = req.headers.range;
if (!range) {
  res.status(400).send('Requires Range header');
} else {
  // Create response headers
  const start = Number(range.replace(/\D/g, ''));
  const end = file.length - 1;

  const contentLength = end - start + 1;
  const headers = {
    'Content-Range': `bytes ${start}-${end}/${file.length}`,
    'Accept-Ranges': 'bytes',
    'Content-Length': contentLength,
  };

  // HTTP Status 206 for Partial Content
  res.writeHead(206, headers);

  const bucket = new mongoose.mongo.GridFSBucket(mongoose.connection.db, {
    bucketName: 'uploads',
  });
  const readstream = bucket.openDownloadStream(file._id, {
    start,
    end,
  });

  readstream.pipe(res);
}
});
});

When I use only the final part ( readStream and pipe it ) , the video works fine but it starts playing until it fully loads , but in order to implement the loading by chunks I had to do the other stuff but it doesn't work , here's what I get : Click to see image



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source