-
3-2. 노드 fs로 HTML 파일 읽어서 제공하기Node.js 2023. 4. 13. 11:35
I. fs로 HTML 파일 읽기
// server1.js const http = require('http'); http.createServer((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(8080, () => { // 서버 연결 console.log('8080번 포트에서 서버 대기 중입니다!'); });
예를 들어서, 위와 같은 코드가 있다고 가정해보자.
위와 같이 HTML 내용을 쭉 작성 할 수는 있지만,
아래와 같이 코드가 굉장히 길어지기 때문에 가독성이 현저히 떨어진다.
// server1.js const http = require('http'); http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.write('<h1>Hello Node!</h1>'); res.write('<h1>Hello Node!</h1>'); res.write('<h1>Hello Node!</h1>'); res.write('<h1>Hello Node!</h1>'); res.write('<h1>Hello Node!</h1>'); res.write('<h1>Hello Node!</h1>'); res.write('<h1>Hello Node!</h1>'); res.write('<h1>Hello Node!</h1>'); res.write('<h1>Hello Node!</h1>'); res.write('<h1>Hello Node!</h1>'); res.write('<h1>Hello Node!</h1>'); res.write('<h1>Hello Node!</h1>'); res.end('<p>Hello Server!</p>'); }) .listen(8080, () => { // 서버 연결 console.log('8080번 포트에서 서버 대기 중입니다!'); });
따라서, HTML 문서를 따로 만들어 준 후에,
저번 게시글에서 배웠던 fs를 통해 HTML 파일을 읽어주면 된다.
✨ fs 관련 게시글 : https://junu128.tistory.com/55
2-12. 노드 파일 시스템 사용하기
I. fs 모듈 파일 시스템에 접근하는 모듈 - 파일/폴더 생성, 삭제, 읽기, 쓰기 가능 - 웹 브라우저에서는 제한적이었으나 노드는 권한을 가지고 있음 - 파일 읽기 예제 // readFile.js const fs = require('fs')
junu128.tistory.com
// server2.html (html 문서) <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Node.js 웹 서버</title> </head> <body> <h1>Node.js 웹 서버</h1> <p>만들 준비되셨나요?</p> </body> </html>
// server2.js const http = require('http'); const fs = require('fs').promises; http.createServer(async (req, res) => { try { const data = await fs.readFile('./server2.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/plain; charset=utf-8' }); res.end(err.message); } }) .listen(8081, () => { console.log('8081번 포트에서 서버 대기 중입니다!'); });
✨ 위 코드에서 catch 문에는 에러처리 내용이 작성되어 있다.
에러 처리를 해주지 않는다면, 에러 발생 시 서버가 멈춰버리기 때문에 catch문 안에 에러처리를 해주는 것이 좋다.
실행 후에 웹 브라우저에 localhost:8081 를 치면 아래와 같은 창이 뜨는 걸 볼 수 있다.
'Node.js' 카테고리의 다른 글
3-4. 노드 POST, PUT, DELETE 요청 보내기 / HTTP status 코드(상태코드) (0) 2023.04.13 3-3. 노드 REST API 서버 만들기 (0) 2023.04.13 3-1. 노드 HTTP 서버와 클라이언트 (0) 2023.04.13 2-16. 노드 에러 처리하기(예외 처리하기) (0) 2023.04.12 2-15. 노드 스레드풀과 커스텀 이벤트 (0) 2023.04.12