Skip to content

Instantly share code, notes, and snippets.

@antonywu
Created May 19, 2013 02:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antonywu/5606489 to your computer and use it in GitHub Desktop.
Save antonywu/5606489 to your computer and use it in GitHub Desktop.
NodeJS Based Basic Static Server
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.htm';
console.log('request starting...' + request.url);
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.jpg':
contentType = 'image/jpeg';
break;
case '.swf':
contentType = 'application/x-shockwave-flash';
break;
}
path.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
response.writeHead(500);
response.end();
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}
else {
response.writeHead(404);
response.end();
}
});
}).listen(8125);
console.log('Server running at http://127.0.0.1:8125/');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment