Skip to content

Instantly share code, notes, and snippets.

@Filirom1
Forked from ryanflorence/static_server.js
Last active December 12, 2015 09:39
Show Gist options
  • Save Filirom1/4753684 to your computer and use it in GitHub Desktop.
Save Filirom1/4753684 to your computer and use it in GitHub Desktop.
static server using streams
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;
}
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
response.writeHead(200);
fs.createReadStream(filename).pipe(response);
});
}).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