Skip to content

Instantly share code, notes, and snippets.

@amadden80
Created December 31, 2014 18:26
Show Gist options
  • Save amadden80/91934849265b717f9f66 to your computer and use it in GitHub Desktop.
Save amadden80/91934849265b717f9f66 to your computer and use it in GitHub Desktop.
Small Node Static File Server
var port = parseInt(process.argv[2]) || 8000;
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
var filePath = request.url;
if (filePath == '/') { filePath = '/index.html'; }
filePath = "./static" + filePath;
var contentType;
switch (path.extname(filePath)) {
case '.html':
contentType = 'text/html';
break;
case '.css':
contentType = 'text/css';
break;
case '.js':
contentType = 'text/javascript';
break;
}
var logMessage = ("\n " + filePath + "\n " + contentType + "\n ");
fs.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
response.writeHead(500);
console.log((new Date()).toTimeString(), logMessage, "------------------ 500\n");
consoel.log(content);
response.end();
} else {
response.writeHead(200, { 'Content-Type': contentType });
console.log((new Date()).toTimeString(), logMessage, "------------------ 200\n");
response.end(content, 'utf-8');
}
});
} else {
response.writeHead(404);
console.log((new Date()).toTimeString(), logMessage, "------------------ 404\n");
response.end();
}
});
}).listen(port);
console.log('...listening on port ' + port + '\n\n');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment