Created
July 30, 2016 09:00
-
-
Save drodsou/f558db8722bc59fe122ed2608331cdf3 to your computer and use it in GitHub Desktop.
Like http-server but just one function with no dependencies
This file contains 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
// ------------------------------------- | |
function httpServeFolder(baseDir, port) { | |
http.createServer(function (request, response) { | |
var filePath = baseDir + request.url.split('?')[0]; | |
if (!path.extname(filePath)) filePath = filePath + (filePath[filePath.length-1]=='/' ? '' : '/') + 'index.html'; | |
var extname = path.extname(filePath) | |
var exttype = {'.html':'text/html', '.js':'text/javascript', '.css' :'text/css', '.json':'application/json', '.png':'image/png', '.jpg':'image/jpg', '.ico':'image/x-icon'} | |
var contentType = (exttype[extname]) ? (exttype[extname]) : 'text/plain'; | |
fs.readFile(filePath, function(error, content) { | |
if (error) { | |
console.log('httpServeFolder: NOT FOUND:',filePath) | |
response.writeHead(404, { 'Content-Type': 'text/plain' }); // TODO: check this | |
response.end("NOT FOUND: " + filePath, 'utf-8'); | |
} | |
else { | |
response.writeHead(200, { 'Content-Type': contentType }); | |
response.end(content, 'utf-8'); | |
} | |
}); | |
}).listen(HTTP_PORT); | |
console.log(`Server running at: http://localhost:${port}`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment