Skip to content

Instantly share code, notes, and snippets.

@edeustace
Forked from ryanflorence/static_server.js
Last active December 21, 2015 08:38
Show Gist options
  • Save edeustace/6279219 to your computer and use it in GitHub Desktop.
Save edeustace/6279219 to your computer and use it in GitHub Desktop.
Server large files with a stream.
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs")
port = process.argv[2] || 8888;
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname
, filename = path.join(process.cwd(), uri);
path.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
fs.stat(filename, function(error, stat) {
if (error) { throw error; }
response.writeHead(200, { 'Content-Length' : stat.size });
var readStream = fs.createReadStream(filename);
readStream.on('open', function () {
// This just pipes the read stream to the response object (which goes to the client)
readStream.pipe(response);
});
readStream.on('error', function(err) {
response.end(err);
});
});
});
}).listen(parseInt(port, 10));
console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment