Skip to content

Instantly share code, notes, and snippets.

@twolfson
Forked from pdeschen/static-server.js
Created April 27, 2012 08:49
Show Gist options
  • Save twolfson/2507569 to your computer and use it in GitHub Desktop.
Save twolfson/2507569 to your computer and use it in GitHub Desktop.
Quick and dirty file server
// Attribution to http://blog.rassemblr.com/2011/04/a-working-static-file-server-using-node-js/
var libpath = require('path'),
http = require("http"),
fs = require('fs'),
url = require("url")/* ,
mime = require('mime') */;
var path = ".";
var port = 8080;
http.createServer(function (request, response) {
var uri = url.parse(request.url).pathname;
var filename = libpath.join(path, uri);
if (path.indexOf('..') !== -1) {
response.writeHead(404, {
"Content-Type": "text/plain"
});
response.write("404 Not Found\n");
response.end();
return;
}
libpath.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.readFile(filename, "binary", function (err, file) {
if (err) {
response.writeHead(500, {
"Content-Type": "text/plain"
});
response.write(err + "\n");
response.end();
return;
}
/* var type = mime.lookup(filename); */
response.writeHead(200/* , {
"Content-Type": type
} */);
response.write(file, "binary");
response.end();
});
});
}).listen(port);
console.log('Listening at ' + port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment