Skip to content

Instantly share code, notes, and snippets.

@satakagi
Last active May 17, 2021 09:52
Show Gist options
  • Save satakagi/82698a74c8ebb0eb72584dda4cbfb3a9 to your computer and use it in GitHub Desktop.
Save satakagi/82698a74c8ebb0eb72584dda4cbfb3a9 to your computer and use it in GitHub Desktop.
node.jsの基本モジュールで、動的なウェブサービスと、静的なウェブコンテンツを配信するウェブサーバを100行でつくる
// very tiny node webserver framework
// based on https://developer.mozilla.org/ja/docs/Learn/Server-side/Node_server_without_framework
// ESModuleで統一 ただ、package.jsonに、{"type":"module"} を設定する必要があります。拡張子(.js)を付けるとダメ?・・・微妙な仕様ですね>node.js
import http from "http";
import fs from "fs";
import path from "path";
var mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.wav': 'audio/wav',
'.mp4': 'video/mp4',
'.woff': 'application/font-woff',
'.ttf': 'application/font-ttf',
'.eot': 'application/vnd.ms-fontobject',
'.otf': 'application/font-otf',
'.svg': 'application/image/svg+xml'
};
http.createServer(function (request, response) {
var rurl = new URL(request.url,"http://localhost");
var filePath = '.' + rurl.pathname;
if (filePath.endsWith("/")) {
filePath = filePath + 'index.html';
}
var extname = String(path.extname(filePath)).toLowerCase();
// console.log('request ', rurl, " filePath:",filePath," extn:",extname," mimeTypes:",mimeTypes," tp:",mimeTypes[extname]);
var contentType = mimeTypes[extname] || 'application/octet-stream';
console.log('request ', request.url, " filePath:",filePath, " contentType:",contentType);
if ( services[rurl.pathname] ){
respDynamic(services[rurl.pathname], response, contentType, rurl);
} else {
respStatic(filePath,response, contentType);
}
}).listen(8080);
console.log('Server running at http://127.0.0.1:8080/');
function respStatic(filePath, response, contentType){
fs.readFile(filePath, function(error, content) {
if (error) {
if(error.code == 'ENOENT') {
fs.readFile('./404.html', function(error, content) {
response.writeHead(200, { 'Content-Type': mimeTypes[".html"] });
response.end(content, 'utf-8');
});
}
else {
response.writeHead(500);
response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
response.end();
}
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}
function respDynamic(func, response, contentType, rurl){
func(response, contentType, rurl);
}
// 動的サービスをこのオブジェクトに登録する
var services ={
"/getTime.json": getTimeFunc,
// path : function
};
// 動的サービスの例
function getTimeFunc(resp, contentType, rurl){
var ansObj = {};
ansObj.time = new Date().getTime();
ansObj.search = rurl.search;
resp.writeHead(200, {'Content-Type': contentType});
resp.write(JSON.stringify(ansObj));
resp.end();
}
function setDynamicService(path,svfunc){
if ( !services[path] && path.startsWith("/")){
services[path]=svfunc;
}
}
export default setDynamicService;
import setDynamicService from "./server.js";
console.log("Hello");
function testjsonout(resp, contentType, rurl){
console.log("called testjsonout");
resp.writeHead(200, {'Content-Type': contentType});
var ans = {};
ans.message="hello";
resp.write(JSON.stringify(ans));
resp.end();
}
setDynamicService("/test.json",testjsonout);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment