Skip to content

Instantly share code, notes, and snippets.

@gitawego
Last active August 29, 2015 14:21
Show Gist options
  • Select an option

  • Save gitawego/1af16328657fb015aa59 to your computer and use it in GitHub Desktop.

Select an option

Save gitawego/1af16328657fb015aa59 to your computer and use it in GitHub Desktop.
/**
* media streaming
* @method streamMedia
* @param {String} path file path
* @param {Object} ioArgs a http connection
* @param {Object} ioArgs.req request object of a http connection
* @param {Object} ioArgs.res response object of a http connection
* @param {Object} ioArgs.next passe to not found
*/
function streamMedia(path, ioArgs) {
fs.stat(path, function (err, stats) {
if (err) {
PlusNode.log.warn(err);
return ioArgs.next();
}
var opt = {
"flags":"r",
'bufferSize':64 * 1024
};
if (ioArgs.req.headers.range) {
var range = ioArgs.req.headers.range;
var total = stats.size;
var parts = range.replace(/bytes=/, "").split("-");
var start = +parts[0];
var end = +parts[1] || total - 1;
var chunksize = end - start + 1;
opt.start = start;
opt.end = end;
ioArgs.res.writeHead(206,
{
"Content-Range":"bytes " + start + "-" + end + "/" + total,
"Accept-Ranges":"bytes",
"Content-Length":chunksize,
"Content-Type":mime.lookup(path),
"Last-Modified":stats.mtime
});
}
fs.createReadStream(path, opt).pipe(ioArgs.res);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment