BackEnd/개념정리
Node로 서버 시작하기 - CodeHan의 코딩공부
CoderHan
2022. 9. 11. 09:48
반응형
Node로 바로 서버를 만들어서 실행하는 방법을 알아보겠다.
우선 vscode나 본인이 사용하는 CodeEditer를 켠다.
const fs = require('fs');
const http = require('http');
const server= http.createServer((req,res) => {
const url = req.url;
res.setHeader('Content-Type', 'text/html');
if(url=== '/') {
const read = fs.createReadStream('./html/index.html');
read.pipe(res);
} else if (url === '/course') {
const read = fs.createReadStream('./html/course.html');
read.pipe(res);
} else {
const read = fs.createReadStream('./html/notfound.html');
read.pipe(res);
}
})res.end();})
server.listen(8080)
이처럼 코드 몇 줄로 서버를 만들 수 있다.
1. 코드를 해석하자면 http와 fs를 requre한다.
2. createServer로 server를 생성한다.
3. url과 header를 정의하고 각 url에 따라 res를 createReadSteam과 pipe로 전달해준다.
4. /html/xxx.index 파일을 응답으로 받을 수 있다.
Node는 서버 만들기가 참 간단하다!
반응형