Skip to content

Instantly share code, notes, and snippets.

@h4ck4life
Forked from serverwentdown/static_server.js
Created March 18, 2014 03:50
Show Gist options
  • Save h4ck4life/9613243 to your computer and use it in GitHub Desktop.
Save h4ck4life/9613243 to your computer and use it in GitHub Desktop.
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