Skip to content

Instantly share code, notes, and snippets.

@linuxenko
Forked from bnerd/index.js
Created February 19, 2016 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save linuxenko/8b99be59439045b01c7a to your computer and use it in GitHub Desktop.
Save linuxenko/8b99be59439045b01c7a to your computer and use it in GitHub Desktop.
Serve large files with Node.js
var libpath = require('path');
var http = require('http');
var fs = require('fs');
var url = require('url');
var bind_port = 8001;
var path = "/path/to/your/base_directory/";
http.createServer(function (request, response) {
var uri = url.parse(request.url).pathname;
var filename = libpath.join(path, uri);
libpath.exists(filename, function (exists) {
if (!exists) {
console.log('404 File Not Found: ' + filename);
response.writeHead(404, {
"Content-Type": "text/plain"
});
response.write("404 Not Found\n");
response.end();
return;
} else{
console.log('Starting download: ' + filename);
var stream = fs.createReadStream(filename, { bufferSize: 64 * 1024 });
stream.pipe(response);
}
});
}).listen(bind_port);
console.log('Download Server listening on Port' + bind_port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment