Created
May 16, 2018 01:29
-
-
Save Gopikrishna19/935ae7183afec6e4eeb7b83a9ab67d63 to your computer and use it in GitHub Desktop.
Node js static http server
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
const chalk = require('chalk'); | |
const fs = require('fs'); | |
const http = require('http'); | |
const path = require('path'); | |
const url = require('url'); | |
const mimeType = { | |
'.html': 'text/html', | |
'.js': 'text/javascript', | |
'.css': 'text/css', | |
'.svg': 'image/svg+xml' | |
}; | |
const colors = { | |
fail: chalk.red.bold, | |
success: chalk.green | |
}; | |
const staticHandler = (req, res) => { | |
let filename = decodeURI(url.parse(req.url).pathname); | |
let pathname = path.join(__dirname, 'dist', filename); | |
const logPrefix = `${chalk.yellow(req.method)} ${chalk.blueBright(req.url)} ->`; | |
fs.exists(pathname, (exists) => { | |
if (!exists) { | |
console.log(logPrefix, colors.fail('404')); | |
res.statusCode = 404; | |
res.end('Not Found!'); | |
return; | |
} | |
if (fs.statSync(pathname).isDirectory()) { | |
pathname = path.join(pathname, 'index.html'); | |
} | |
fs.readFile(pathname, (error, data) => { | |
if (error) { | |
console.log(logPrefix, colors.fail('500', error.toString())); | |
res.statusCode = 500; | |
res.end(`Error getting the file:${error}`); | |
} else { | |
const extension = path.parse(pathname).ext; | |
console.log(logPrefix, colors.success(path.relative(__dirname, pathname))); | |
res.setHeader('Content-Type', mimeType[extension] || 'text/plain'); | |
res.end(data); | |
} | |
}); | |
}); | |
}; | |
http | |
.createServer(staticHandler) | |
.listen(8080); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment