-
-
Save serverwentdown/9304183 to your computer and use it in GitHub Desktop.
Node.JS static file web server. Put it in your path to fire up servers in any directory, takes an optional port argument. (Modded for larger files)
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] || 4002; | |
http.createServer(function(request, response) { | |
var uri = url.parse(request.url).pathname | |
, filename = decodeURIComponent(path.join(process.cwd(), uri)); | |
console.log(uri); | |
fs.exists(filename, function(exists) { | |
if(!exists) { | |
response.writeHead(404, {"Content-Type": "text/plain"}); | |
response.write("404 Not Found\n"); | |
response.end(); | |
return; | |
} | |
if (fs.statSync(filename).isDirectory()) filename += '/index.html'; | |
fs.exists(filename, function(exists) { | |
if (!exists) { | |
response.writeHead(404, {"Content-Type": "text/plain"}); | |
response.write("No index.html file. \n"); | |
response.end(); | |
return; | |
} | |
var readstream = fs.createReadStream(filename); | |
response.writeHead(200); | |
// readstream.setEncoding("binary"); | |
readstream.pipe(response); | |
// readstream.on('data', function (chunk) { | |
// response.write(chunk, 'binary'); | |
// }); | |
// readstream.on('end', function () { | |
// console.log('served ' + filename + ''); | |
// response.end(); | |
// }); | |
readstream.on('error', function(err) { | |
response.write(err + "\n"); | |
response.end(); | |
return; | |
}); | |
}); | |
}); | |
}).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
Thanks a lot for the gist!