Skip to content

Instantly share code, notes, and snippets.

@logue
Created August 17, 2018 00:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save logue/ce8cb2fcc2e6ae8eae6536c3b4e76942 to your computer and use it in GitHub Desktop.
Save logue/ce8cb2fcc2e6ae8eae6536c3b4e76942 to your computer and use it in GitHub Desktop.
node.jsによる簡易サーバー。node server.jsとタイプすると、distディレクトリをドキュメントルートとしてWebサーバーが起動する。
/*!
* @file server.js
* @copyright © 2018 By Logue <http://logue.be/>.
* @license MIT
*/
const http = require("http");
const fs = require('fs');
function getType(_url) {
const types = {
".html": "text/html",
".css": "text/css",
".js": "text/javascript",
".png": "image/png",
".jpg": "image/jpeg",
".gif": "image/gif",
".svg": "image/svg+xml",
".svgz": "image/svg+xml"
}
for (var key in types) {
if (_url.endsWith(key)) {
return types[key];
}
}
return "text/plain";
}
const server = http.createServer(function(req, res) {
const url = "dist" + (req.url.endsWith("/") ? req.url + "index.html" : req.url);
if (fs.existsSync(url)) {
fs.readFile(url, (err, data) => {
if (!err) {
console.log('\u001b[36mFetch: \u001b[0m', url);
res.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"Content-Type": getType(url)
});
res.end(data);
} else {
console.error('\u001b[31mError: \u001b[0m', url);
res.statusCode = 500;
res.end();
}
});
} else {
console.error('\u001b[35mNot Found: \u001b[0m', url);
res.statusCode = 404;
res.end();
}
});
const port = process.env.PORT || 3000;
server.listen(port, function() {
console.log("To view your app, open this link in your browser: http://localhost:" + port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment