웹 서버에 SSL 암호를 거는 모듈 제공
https의 port는 443
const https = require('https');
const fs = require('fs');
//서버가 시작되기 전에 인증서를 읽고 넣어줘야함
//인증서: cert, key, ca -> fs로 가져와야함
//https로 하면 port가 443
https.createServer({
cert: fs.readFileSync('도메인 인증서 경로'),
key: fs.readFileSync('도메인 비밀키 경로'),
ca: [
fs.readFileSync('상위 인증서 경로'),
fs.readFileSync('상위 인증서 경로'),
],
}, (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.write('<h1>Hello Node!</h1>');
res.end('<p>Hello Server!</p>');
})
.listen(443, () => {
console.log('443번 포트에서 서버 대기 중입니다!');
});
SSL 암호화와 더불어 최신 HTTP 프로토콜인 http/2를 사용하는 모듈
요청 및 응답 방식이 기존 http/1.1보다 개선됨
웹의 속도가 개선됨
요청을 하나씩(http)이 아닌 여러개를 동시에 보낼 수 있음
//http2
const http2 = require('http2');
const fs = require('fs');
//여기도 인증서 가져와야함
//port 443
http2.createSecureServer({
cert: fs.readFileSync('도메인 인증서 경로'),
key: fs.readFileSync('도메인 비밀키 경로'),
ca: [
fs.readFileSync('상위 인증서 경로'),
fs.readFileSync('상위 인증서 경로'),
],
}, (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.write('<h1>Hello Node!</h1>');
res.end('<p>Hello Server!</p>');
})
.listen(443, () => {
console.log('443번 포트에서 서버 대기 중입니다!');
});
원래 nodejs는 단일 스레드에서 동작 -> 하나의 cpu 코어만 사용
Cluster -> 여러 개의 프로세스를 생성하여 모든 CPU 코어를 사용가능
요청이 많이 들어왔을 때 병렬로 실행된 서버의 개수만큼 요청이 분산됨->서버에 무리가 덜감
cluster로 코어 하나 당 노드 프로세스 하나를 배정 가능
단점: 컴퓨터 자원(메모리 세션 등) 공유 못함
워커스레드 기능과 유사
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`마스터 프로세스 아이디: ${process.pid}`);
// CPU 개수만큼 워커를 생산
for (let i = 0; i < numCPUs; i += 1) {
cluster.fork();
}
// 워커가 종료되었을 때
cluster.on('exit', (worker, code, signal) => {
console.log(`${worker.process.pid}번 워커가 종료되었습니다.`);
console.log('code', code, 'signal', signal);
cluster.fork();
});
} else {
// 워커들이 포트에서 대기
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.write('<h1>Hello Node!</h1>');
res.end('<p>Hello Cluster!</p>');
setTimeout(() => { // 워커 존재를 확인하기 위해 1초마다 강제 종료
process.exit(1);
}, 1000);
}).listen(8086);
console.log(`${process.pid}번 워커 실행`);
}