V8 엔진
자바스크립트 코드를 인터프리터 방식으로 해석 X
비동기 + 이벤트 기반
웹에 최적화
http
모듈 기반 웹 서버 제작
const http = require('http'); // http 라이브러리 require()포함시시킨다는 것
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => { // createServer() : http 모듈로 서버를 1개 생성하는 기능
// 내부에 req, res 콜백 함수 존재
res.statusCode = 200;
res.setHeader('Content-type', 'text/plain');
res.end('Hello js world');
});
server.listen(port, hostname, () => { // Client가 서버에 접속하기 전까지 대기(리스너)
console.log(`Server running at http://${hostname}:${port}/`);
});
npm httpServer.js
127.0.0.1:3000 or localhost:3000 으로 확인
(127.0.0.1:3000 >> localhost:3000, 속도 츨면)
이벤트 기반
이벤트
: 특정 버튼 클릭 등등콜백 함수
: 이벤트 발생시 발동하는 것함수 구현
: 사용자
호출
: 사용자 X, 이벤트 발생 시 이벤트 리스너에 의해 발생
Non-blocking I/O
일단 모든 요청 전부 다 받음
요청 순서에 따라서 응답을 주는 것이 아닌 완료된 순서로 먼저 주는 것
블로킹
논블로킹
package.json 파일 생성
http
는 모듈 기반
express
는 http보다 확장성 + 편의 기능 추가
된 웹 서버 라이브러리 제공
// package.json 생성하기
npm init
{
"name": "board",
"version": "1.0.0",
"description": "",
"main": "server.js",
"dependencies": {
"express": "^4.18.2"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "lch",
"license": "ISC"
}
// express 설치
npm install express
// node_modules 에 많은 파일 존재 -> express 설치시 관련 라이브러리 전부 가져온 것
const express = require('express'); // express 라이브러리 사용해서 express 객체 생성
const app = express(); // express 사용해서 새로운 app 객체 생성, app : 서버 객체라고 생각
// listen(포트번호, 실행할 코드)
app.listen(8080, function(){ // listen : 서버 띄우고 client 객체의 요청 기다림, function() : 서버 구동시 콜백함수
console.log("포트 8080으로 서버 대기중.......")
});
npm Server.js
// localhost:8080
const express = require('express'); // express 라이브러리 사용해서 express 객체 생성
const app = express(); // express 사용해서 새로운 app 객체 생성, app : 서버 객체라고 생각
// listen(포트번호, 실행할 코드)
app.listen(8080, function(){ // listen : 서버 띄우고 client 객체의 요청 기다림, function() : 서버 구동시 콜백함수
console.log("포트 8080으로 서버 대기중.......")
});
// get(웹 브라우저 요청한 요청 url, 요청을 처리하는 콜백 함수)
// 콜백함수(req, res)
app.get('/book', function(req, res) {
res.send('도서 목록 관련 페이지입니다. ');
});
app.get('/', function(req, res) {
res.send('홈 페이지');
});
send()
: 요청한 웹 브라우저로 문자열 형식
의 메시지 응답
Server.js 추가
app.get('/book', function(req, res) {
res.send(
'<html>\
<body>\
<h1>홈 페이지입니다.</h1>\
<marquee>송재근님 반갑습니다.</marquee>\ 오른쪽에서 왼쪽 이동
</body>\
</html>'
);
});
sendFile()
: 파일이 웹 브라우저에게 전달
sendFile(보낼 파일 경로)
Server.js 수정
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html'); //__dirname : 현재 디렉토리
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Home</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg bg-body-tertiary">
<div class="container-fluid">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" aria-disabled="true">Disabled</a>
</li>
</ul>
</div>
</div>
</nav>
<h1>홈페이지 입니다.</h1>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-HwwvtgBNo3bZJJLYd8oVXjrBZt8cqVSpeBNS5n7C8IVInixGAoxmnlMuBnhbgrkm" crossorigin="anonymous"></script>
</body>
</html>