Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Node js static http server
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