-
-
Save edeustace/6279219 to your computer and use it in GitHub Desktop.
Server large files with a stream.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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