Last active
September 25, 2015 00:27
-
-
Save nmrugg/833252 to your computer and use it in GitHub Desktop.
A simple node.js web server
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
/*jslint onevar: true, undef: true, newcap: true, nomen: true, regexp: true, plusplus: true, bitwise: true, node: true, indent: 4, white: false */ | |
/// Usage: node static_server.js PORT | |
var http = require("http"), | |
url = require("url"), | |
path = require("path"), | |
fs = require("fs"), | |
qs = require("querystring"), | |
port = process.argv[2] || 80, /// Defaults to port 80 | |
dir = process.argv[2] || process.cwd(); /// Defaults to current working directory | |
/// Start the server. | |
http.createServer(function (request, response) | |
{ | |
var filename, | |
uri = qs.unescape(url.parse(request.url).pathname),; | |
filename = path.join(dir, uri); | |
/// Make sure the URI is valid and withing the current working directory. | |
if (uri.substr(0,4) === "/../" || uri.substr(0, 1) !== "/" || path.relative(dir, filename).substr(0, 3) === "../") { | |
response.writeHead(404, {"Content-Type": "text/plain"}); | |
response.write("404 Not Found\n"); | |
response.end(); | |
return; | |
} | |
fs.stat(filename, function (err, stats) | |
{ | |
if (!err && stats.isDirectory()) { | |
filename += "/index.html"; | |
} | |
fs.exists(filename, function(exists) { | |
if (!exists) { | |
response.writeHead(404, {"Content-Type": "text/plain"}); | |
response.write("404 Not Found\n"); | |
response.end(); | |
return; | |
} | |
response.writeHead(200); | |
/// Stream the data out to prevent massive buffers on large files. | |
fs.createReadStream(filename, {"bufferSize": 4096}).pipe(response); | |
}); | |
}); | |
}).listen(parseInt(port, 10)); | |
console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown"); |
Made sure to parse the URI.
Stream data out to prevent massive buffers on large files.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Made it pass JSLint.