Skip to content

Instantly share code, notes, and snippets.

@icodeforlove
Created September 18, 2012 22:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save icodeforlove/3746561 to your computer and use it in GitHub Desktop.
Save icodeforlove/3746561 to your computer and use it in GitHub Desktop.
Simple file server test for video
/*jshint node:true*/
var fs = require('fs'),
http = require('http'),
path = require('path'),
port = 1338,
dir = '.';
http.createServer(function (request, response) {
var filePath = path.join(dir, path.basename(request.url));
if (path.extname(request.url) !== '.mp4' || !fs.existsSync(filePath)) return throw404();
response.writeHead(200, {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'video/mp4',
'Transfer-Encoding': 'chunked',
'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0'
});
var file_stream = fs.createReadStream(filePath);
file_stream.on('error', function (exception) {
console.error(exception);
});
file_stream.on('data', function (data) {
response.write(data);
});
file_stream.on('close', function () {
if (request.connection.remoteAddress) console.log('served: ' + request.url + ' to ' + request.connection.remoteAddress);
response.end();
});
function throw404() {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.end();
return;
}
}).listen(port);
console.log('mp4 server ready on http://localhost:' + port + ' serving:');
console.log(fs.readdirSync(dir).filter(function (filename) {
return path.extname(filename) === '.mp4';
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment