BackEnd/NodeJs
fs객체를 이용하여 파일 읽기.
3일마다 작심3일
2022. 1. 3. 10:58
Server.js
const http = require('http'); // http 모듈 생성
http.createServer((req, res) => { // http 서버 생성
res.write('<h1>Hello server!</h1>') // html태그 전송
res.end('<h1>Hello hanamDeveloper!</h1>') // 서버 종료와 동시에 html태그 전송
}).listen(8080, () => { // 8080 port로 생성
console.log('포트 8080에서 서버 대기 중입니다.')
})
이런식으로 코드를 구성해도 서버는 잘 구동되지만 html태그를 직접 하면 코드의 줄도 길어질뿐만아니라 행동에도 제약이 생긴다.
그래서 fs객체를 이용해서 파일을 읽어서 코드를 구성한다.
우선 html파일을 만들어준다.
server.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>NodeJS Server2</title>
</head>
<body>
<h1>Node JS Server2</h1>
<p>이렇게 전송</p>
</body>
</html>
Server.js
const http = require('http');
const fs = require('fs').promises;
const server = http.createServer(async(req, res) => {
try{
// 특정 브라우저에서 문자열과 Html태그를 인식하지 못하는 경우가 있어 contentType을 넣어주어야한다.
res.writeHead(200, { 'Content-Type' : 'text/html; charset=utf-8'});
const data = await fs.readFile('./server2.html');
res.end(data)
} catch (error) {
res.writeHead(200, { 'Content-Type' : 'text/plain; charset=utf-8'});
res.end(error.message)
}
}).listen(8080, () => {
console.log('포트 8080에서 서버 대기 중입니다.')
})
추가로 nodejs 는 에러가 생기면 서버 자체가 멈춰버리기때문에 error처리가 필수다.
그래서 try catch를 이용해 에러 처리를 해주었다.