Created
April 21, 2016 08:07
-
-
Save andreasvirkus/b8a85f4b2d52fd01180aee3209da1723 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Basic static server setup with Node.js | |
var http = require("http"), | |
url = require("url"), | |
path = require("path"), | |
fs = require("fs"), | |
contentTypes = require('./content-types'), | |
sysInfo = require('./sys-info'), | |
port = process.argv[2] || 8888; | |
http.createServer(function(request, response) { | |
var uri = url.parse(request.url).pathname, | |
filePath = ~uri.indexOf('/assets/') ? '/../' + uri : '/../build/content' + uri, | |
filename = path.join(__dirname + filePath); | |
// IMPORTANT: Your application HAS to respond to GET /health with status 200 | |
// for OpenShift health monitoring | |
if (uri === '/health') { | |
response.writeHead(200); | |
response.end(); | |
return; | |
} else if (~uri.indexOf('/info')) { | |
response.setHeader('Content-Type', 'application/json'); | |
response.setHeader('Cache-Control', 'no-cache, no-store'); | |
response.end(JSON.stringify(sysInfo.gen())); | |
return; | |
} | |
fs.exists(filename, function(exists) { | |
if (!exists) { | |
response.writeHead(404, {"Content-Type": "text/plain"}); | |
response.write("404 Not Found\n"); | |
response.end(); | |
return; | |
} | |
if (fs.statSync(filename).isDirectory()) filename += '/index.html'; | |
fs.readFile(filename, "binary", function(err, file) { | |
let ext = path.extname(uri).slice(1); | |
if (err) { | |
response.writeHead(500, {"Content-Type": "text/plain"}); | |
response.write(err + "\n"); | |
response.end(); | |
return; | |
} | |
response.setHeader('Content-Type', contentTypes[ext] || "text/html"); | |
response.writeHead(200); | |
response.write(file, "binary"); | |
response.end(); | |
}); | |
}); | |
}).listen(parseInt(port, 10)); | |
console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment