node.js를 이용해서 간단한 웹 서버를 만들어보자.
기본 설정
다음과 같은 코드를 터미널에 쳐서 package.json을 만들다.
bash
npm init -y
package.json을 다음과 같이 만든다.
json
{
"name": "server_build",
"version": "1.0.0",
"main": "createServer.js",
"type": "module", // 이 부분이 추가됨.
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}
html 코드
index.html을 다음과 같이 작성한다.
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>node.js testServer</title>
</head>
<body>
<h1>Node.js webserver</h1>
<p>Are you ready to dive in?</p>
</body>
</html>
서버 코드
javascript
import http from 'http';
import fs from 'fs/promises';
const requestHandler = async (req, res) => {
try {
console.log('연결됨')
const data = await fs.readFile("./index.html");
res.writeHead(200, { 'Content-type': 'text/html; charset=utf-8' });
res.end(data);
} catch (err) {
console.error(err);
res.writeHead(500, { 'Content-type': 'text/html; charset=utf-8' });
res.end(err.message);
}
}
const startServer = () => {
http.createServer(requestHandler)
.listen(8080, () => {
console.log('8080 포트에서 대기중')
})
}
startServer();
특징
- async, await을 이용
설명
res.writeHead() : 응답에 대한 정보를 기록. (HTTP 정보 입력 부분)
res.write() : 실제로 HTML이 담기는 부분
res.end() : 응답 종료를 나타내는 부분