/**
* top.js, main()
*/
"use strict";
// require()
const { print, errPrint, parseCookies } = require(`./_system.js`);
const http = require(`http`);
const fs = require(`fs`);
// constants
const PORT = 8080;
const HTML_PATH = './html/';
// starting point.
// create server.
const server = http.createServer((request, response) => {
const cookies = parseCookies(request.headers.cookie);
print(`${request.url}, ${cookies}`);
response.writeHead(200, { 'Set-Cookie' : 'mc=test'})
fs.readFile(HTML_PATH + 'index.html', (error, data) => {
if(error) errPrint(error);
//response.write('');
response.end(data);
});
});
// port open. server start.
server.listen(PORT);
// add event : listening
server.on(`listening`, () => {
print(`PORT : ${PORT} open. 응답 대기 중..`);
});
// add event : error
server.on(`error`, (error) => {
errPrint(error);
});
/**
* _system.js
*/
"use strict";
const print = text => console.log(text);
const errPrint = text => console.error(text);
if(typeof alert === "undefined") {
//print("alert is undefined.");
//function alert(text) { console.log("alert : ", text) };
var alert = text => print("alert : " + text);
}
const parseCookies = (cookie = '') => {
// name=abc;key=3333;...
return cookie.split(';') // [ name=abc, key=3333, ... ]
.map(v => v.split('=')) // [ [ name, abc ], [ key, 3333 ], ... ]
.map(([k, ... vs]) => {
//print(`k : ${k}, vs.join : ${vs.join('=')}`)
return [k, vs.join('=')]; // return [key, value]
})
.reduce((acc, [k, v]) => {
acc[k.trim()] = decodeURIComponent(v); // acc[key] = value -> { key : value }
return acc;
}, {});
};
module.exports = {
print,
errPrint,
alert,
parseCookies,
}
<!--
file name : index.html
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>node.js web server</title>
</head>
<body>
<p>hrxtssss</p>
</body>
</html>
서버 생성부터 포트 열고 쿠키 파싱 및 전송까지만 실습해보았다.
자바스크립트에서의 map과 reduce 함수는 아직도 좀 아리송하다.