Skip to content

Instantly share code, notes, and snippets.

@rockwood
Created July 19, 2012 16: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 rockwood/3145060 to your computer and use it in GitHub Desktop.
Save rockwood/3145060 to your computer and use it in GitHub Desktop.
Node Static File Server
var http = require('http');
var fs = require('fs');
var path = require('path');
var PORT = 3000;
var INDEX = './index.html';
http.createServer(function (request, response) {
console.log('request starting...');
var filePath = '.' + request.url;
if (filePath == './')
filePath = INDEX;
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
fs.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(PORT);
console.log('Server running at http://127.0.0.1:' + PORT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment