Skip to content

Instantly share code, notes, and snippets.

@rpragana
Created November 30, 2017 18:47
Show Gist options
  • Save rpragana/cf0d66958126e05d095e8c02ce869a25 to your computer and use it in GitHub Desktop.
Save rpragana/cf0d66958126e05d095e8c02ce869a25 to your computer and use it in GitHub Desktop.
Node video streaming

Cria uma stream de vídeo no nodejs plano (sem express ou outros módulos)

#!/usr/bin/env node
var http = require('http'),
fs = require('fs'),
util = require('util');
http.createServer(function (req, res) {
var path = 'movies/video.mp4';
var stat = fs.statSync(path);
var total = stat.size;
console.log("REQUEST: "+JSON.stringify(req.headers));
if (req.headers['range']) {
var range = req.headers.range;
var parts = range.replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
var start = parseInt(partialstart, 10);
var end = partialend ? parseInt(partialend, 10) : total-1;
var chunksize = (end-start)+1;
console.log('RANGE: ' + start + ' - ' + end + ' = ' + chunksize);
var file = fs.createReadStream(path, {start: start, end: end});
res.writeHead(206, { 'Content-Range': 'bytes ' + start + '-' +
end + '/' + total, 'Accept-Ranges': 'bytes',
'Content-Length': chunksize, 'Content-Type': 'video/mp4' });
file.pipe(res);
} else {
console.log('ALL: ' + total);
res.writeHead(200, { 'Content-Length': total,
'Content-Type': 'video/mp4' });
fs.createReadStream(path).pipe(res);
}
}).listen(8700, '127.0.0.1');
console.log('Servidor rodando em http://127.0.0.1:8700/');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment