Skip to content

Instantly share code, notes, and snippets.

@derMani
Forked from psi-4ward/GridStream.js
Last active September 5, 2020 19:07
Show Gist options
  • Save derMani/218bd18cc926d85a57a1 to your computer and use it in GitHub Desktop.
Save derMani/218bd18cc926d85a57a1 to your computer and use it in GitHub Desktop.
NodeJS MongoDB-GridFS Video range stream exampleLets your browser seek/jump wihin the video-playback.
var express = require('express');
var app = express();
var mongo = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var GridStore = mongo.GridStore;
var ObjectID = require('mongodb').ObjectID;
function StreamGridFile(req, res, GridFile) {
if(req.headers['range']) {
// Range request, partialle stream the file
console.log('Range Reuqest');
var parts = req.headers['range'].replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
var start = parseInt(partialstart, 10);
var end = partialend ? parseInt(partialend, 10) : GridFile.length -1;
var chunksize = (end-start)+1;
res.writeHead(206, {
'Content-disposition': 'filename=xyz',
'Accept-Ranges': 'bytes',
'Content-Type': GridFile.contentType,
'Content-Range': 'bytes ' + start + '-' + end + '/' + GridFile.length,
'Content-Length': chunksize
});
// Set filepointer
GridFile.seek(start, function() {
// get GridFile stream
var stream = GridFile.stream(true);
// write to response
stream.on('data', function(buff) {
// count data to abort streaming if range-end is reached
// perhaps theres a better way?
if(start >= end) {
// enough data send, abort
GridFile.close();
res.end();
} else {
res.write(buff);
}
});
});
} else {
// stream back whole file
console.log('No Range Request');
res.header('Content-Type', GridFile.contentType);
res.header('Content-Length', GridFile.length);
var stream = GridFile.stream(true);
stream.pipe(res);
}
}
app.get('/files/get/:file', function(req, res) {
new GridStore(db, new ObjectID(req.params.file), null, 'r').open(function(err, GridFile) {
if(!GridFile) {
res.send(404,'Not Found');
return;
}
StreamGridFile(req, res, GridFile);
});
});
app.use('/', express.static(__dirname + '/client', { maxAge: 0 }));
// Initialize MongoDB connection once
MongoClient.connect("mongodb://localhost/test", function(err, database) {
if(err) throw err;
db = database;
});
app.listen(8080); // <<---- Start Listening to Port
@kartik1225
Copy link

Works Perfect 🙌🏻

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment