이전 글 <Node로 기본적인 웹 서버 만들기> 에서 만든 기본적인 웹 서버를 더 발전시켜보자!
// helloworld.js
const http = require('http');
const port = process.env.PORT || 3000;
const server = http.createServer((req, res) => {
// 쿼리스트링, 옵션인 마지막 슬래시를 없애고 소문자로 바꿔서 url을 정규화한다.
const path = req.url.replace(/\/?(?:\?.*)?$/, '').toLowerCase()
switch(path) {
case '':
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Homepage')
break
case '/about':
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('About')
break
default:
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Not Found')
break
}
})
server.listen(port, () => console.log(`server started on port ${port}; press Ctrl-C to terminate....`))
<img src="/img/logo.png alt="logo">
와 같이 로고 파일을 링크한다.// helloworld.js
const http = require('http');
const fs = require('fs')
const port = process.env.PORT || 3000;
function serveStaticFile(res, path, contentType, responseCode = 200) {
fs.readFile(__dirname + path, (err, data) => {
if(err) {
res.writeHead(500, { 'Content-Type': 'text/plain' })
return res.end('500 - Internal Error')
}
res.writeHead(responseCode, { 'Content-Type': contentType })
res.end(data)
})
}
const server = http.createServer((req, res) => {
// 쿼리스트링, 옵션인 마지막 슬래시를 없애고 소문자로 바꿔서 url을 정규화한다.
const path = req.url.replace(/\/?(?:\?.*)?$/, '').toLowerCase()
switch(path) {
case '':
serveStaticFile(res, '/public/home.html', 'text/html')
break
case '/about':
serveStaticFile(res, '/public/about.html', 'text/html')
break
case '/img/image.png':
serveStaticFile(res, '/public/img/image.png', 'image/png')
break
default:
serveStaticFile(res, '/public/404.html', 'text/html', 404)
break
}
})
server.listen(port, () => console.log(`server started on port ${port}; press Ctrl-C to terminate....`))
const fs = require('fs')
fs.readFile(파일의 경로, 인코딩, 콜백함수)
<참고>