Skip to content

Instantly share code, notes, and snippets.

@leodagdag
Created November 5, 2012 09:31
Show Gist options
  • Save leodagdag/4016317 to your computer and use it in GitHub Desktop.
Save leodagdag/4016317 to your computer and use it in GitHub Desktop.
very simple HTTP server with Nodejs
var http = require('http'),
url = require('url'),
path = require('path'),
fs = require('fs');
var mimeTypes = {
"html": "text/html",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"js": "text/javascript",
"css": "text/css",
"json":"application/json"};
http.createServer(function(req, res) {
var uri = url.parse(req.url).pathname;
var filename = path.join(process.cwd(), uri);
fs.exists(filename, function(exists) {
if(!exists) {
console.log("not exists: " + filename);
res.writeHead(404, {'Content-Type': 'text/plain'});
res.write('404 Not Found\n');
res.end();
return;
}
var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
res.writeHead(200, {'Content-Type':mimeType});
var fileStream = fs.createReadStream(filename);
fileStream.pipe(res);
}); //end path.exists
}).listen(1337);
console.log("Server running...")
setInterval(function(){
console.log("Alive !")
}, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment