Skip to content

Instantly share code, notes, and snippets.

@napcs
Created February 20, 2013 19:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save napcs/4998420 to your computer and use it in GitHub Desktop.
Save napcs/4998420 to your computer and use it in GitHub Desktop.
Simple web server with MIME type support and directory listing support for use in HTML5 and CSS3 Second Edition.
// Simple static server with MIME based on https://gist.github.com/906395
// Definitely not for production use.
var path = require('path');
var http = require("http");
var fs = require('fs');
var url = require("url");
try{
var mime = require('mime');
} catch(error) {
console.log("**** UNABLE TO START. Please install the MIME library with\n\n \tnpm install mime\n\n and restart.");
return;
}
var directory = ".";
var port = 8080;
var server = http.createServer(function (request, response) {
var uri = url.parse(request.url).pathname;
var filename = path.join(directory, 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()) {
if (fs.existsSync(filename + 'index.html')) {
filename += 'index.html';
}else{
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('<html><head><title>Listing " + filename + "</title></head>');
response.write('<body><h2>Index of ' + filename + '</h2><ul>');
response.write('<li><a href="' + path.join(uri,"../") + '">..</a></li>');
fs.readdir(filename, function(err, files) {
if (err) {
console.log('Error reading directory:', err);
}else{
for (var index in files) {
var file = files[index];
var slash = fs.statSync(path.join(filename, file)).isDirectory() ? '/' : ''
var output = '<li><a href="' + path.join(uri, file)
+ slash +'">' + file + slash + '</a></li>';
response.write(output);
}
}
response.end('</u></body></html>');
console.log("Serving directory listing for " + filename);
return;
});
}
}
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
});
console.log("Serving " + filename);
response.write(file, "binary");
response.end();
});
});
});
server.listen(port);
console.log("Listening on port " + port + ". Press CTRL+C to stop.");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment