Skip to content

Instantly share code, notes, and snippets.

@drodsou
Created July 30, 2016 09:00
Show Gist options
  • Save drodsou/f558db8722bc59fe122ed2608331cdf3 to your computer and use it in GitHub Desktop.
Save drodsou/f558db8722bc59fe122ed2608331cdf3 to your computer and use it in GitHub Desktop.
Like http-server but just one function with no dependencies
// -------------------------------------
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