Skip to content

Instantly share code, notes, and snippets.

@rpavlovic
Created February 12, 2015 18:15
Show Gist options
  • Save rpavlovic/019b7a788a8c892951e9 to your computer and use it in GitHub Desktop.
Save rpavlovic/019b7a788a8c892951e9 to your computer and use it in GitHub Desktop.
simple Node.js server
// A very basic web server in node.js
// Stolen from: Node.js for Front-End Developers by Garann Means (p. 9-10)
var port = 8000;
var serverUrl = "127.0.0.1";
var http = require("http");
var path = require("path");
var fs = require("fs");
console.log("Starting web server at " + serverUrl + ":" + port);
http.createServer( function(req, res) {
var now = new Date();
var filename = req.url || "index.html";
var ext = path.extname(filename);
var localPath = __dirname;
var validExtensions = {
".html" : "text/html",
".js": "application/javascript",
".css": "text/css",
".txt": "text/plain",
".jpg": "image/jpeg",
".gif": "image/gif",
".png": "image/png",
".json": "application/json",
".ico": "image/x-icon"
};
var isValidExt = validExtensions[ext];
if (isValidExt) {
localPath += filename;
path.exists(localPath, function(exists) {
if(exists) {
console.log("Serving file: " + localPath);
getFile(localPath, res, ext);
} else {
console.log("File not found: " + localPath);
res.writeHead(404);
res.end();
}
});
} else {
console.log("Invalid file extension detected: " + ext)
}
}).listen(port, serverUrl);
function getFile(localPath, res, mimeType) {
fs.readFile(localPath, function(err, contents) {
if(!err) {
res.setHeader("Content-Length", contents.length);
res.setHeader("Content-Type", mimeType);
res.statusCode = 200;
res.end(contents);
} else {
res.writeHead(500);
res.end();
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment