Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@parikh5555
Forked from hectorcorrea/webserver.js
Last active July 29, 2016 10:23
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 parikh5555/021c4caae573386fddd8586bdfe32cce to your computer and use it in GitHub Desktop.
Save parikh5555/021c4caae573386fddd8586bdfe32cce to your computer and use it in GitHub Desktop.
web server in node.js
var http = require("http");
var express = require("express")
var fs = require("fs")
var port = "8081";
var serverURL = "127.0.0.1";
var path = require("path")
console.log('Server running at ' + serverURL + ":" + port);
http.createServer(function (request, response) {
var filename = request.url || "Energy.html";
var now = new Date();
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"
};
var isValidExt = validExtensions[ext];
if (isValidExt) {
localpath += filename;
fs.exists(localpath, function(exists){
if(exists){
console.log("Serving File:" + filename)
getFile(localpath, response, ext);
}
else {
console.log("File not Found:"+ filename)
res.writeHead(404);
res.end();
}
});
}
else {
console.log("Invalid extension:" +ext)
}
}).listen(port, serverURL);
function getFile(localpath, response, mimeType) {
fs.readFile(localpath, function(error, contents){
if(!error) {
response.setHeader("Content-Length", contents.length);
response.setHeader("Content-Length",mimeType);
response.statusCode = 200;
response.end(contents);
} else {
response.writeHead(500);
response.end();
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment