Skip to content

Instantly share code, notes, and snippets.

@rayworks
Forked from icodeforlove/mp4-chunk-test.js
Created November 1, 2022 06:29
Show Gist options
  • Save rayworks/1398d516190dd37547376d03c5dd377c to your computer and use it in GitHub Desktop.
Save rayworks/1398d516190dd37547376d03c5dd377c 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