Skip to content

Instantly share code, notes, and snippets.

@nmrugg
Last active September 25, 2015 00:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmrugg/833252 to your computer and use it in GitHub Desktop.
Save nmrugg/833252 to your computer and use it in GitHub Desktop.
A simple node.js web server
/*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");
@nmrugg
Copy link
Author

nmrugg commented Mar 12, 2011

Made it pass JSLint.

@nmrugg
Copy link
Author

nmrugg commented Oct 5, 2013

Made sure to parse the URI.

@nmrugg
Copy link
Author

nmrugg commented Oct 5, 2013

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