[Node.js] OS module, URL module, HTTP module, Routing,Serving pages

Juyeon Lee·2024년 7월 3일

[새싹x코딩온]

목록 보기
14/23

OS module

OS 모듈은 컴퓨터 운영체제 관련 정보들을 제공하는 메서드이다.

import os from 'os'

console.log(os.platform()) //win32
console.log(os.arch()) //x64
console.log(os.cpus()) // CPU 코어에 대한 정보를 담고 있는 객체 배열
console.log(os.hostname())//시스템의 호스트 이름
console.log(os.homedir())//현재 사용자의 홈 디렉토리
console.log(os.networkInterfaces())//네트워크 인터페이스의 세부 정보를 포함하는 객체
console.log(os.freemem())//시스템에서 사용 가능한 메모리의 양을 바이트 단위로
console.log(os.totalmem())//시스템의 총 메모리 양을 바이트 단위로

URL module

url 관련 정보들을 제공하는 메서드이다.

import {URL} from "url";

const myURL = new URL("https://www.exmaple.com:8080/p/a/t/h?qyery=string#hash");

console.log(myURL.hash) //#hash
console.log(myURL.host) //www.exmaple.com:8080
console.log(myURL.hostname)//www.exmaple.com
console.log(myURL.port)//8080
console.log(myURL.href)//https://www.exmaple.com:8080/p/a/t/h?qyery=string#hash
console.log(myURL.protocol)//https:
console.log(myURL.search)//?qyery=string
console.log(myURL.searchParams)//URLSearchParams { 'qyery' => 'string' }

// Both works the same 
console.log(myURL.toString());
console.log(myURL.toJSON());

마지막 두개는 URL 객체를 string과 json형태로 변환해주는 건데, 결과값이 같다.

HTTP method

HTTP method를 사용하여 서버를 만들어보자. 실무에서는 주로 Express를 이용하지만, 기본적인 HTTP 서버를 이해하는 것도 중요하다.

import http from 'http'

//create our server
const server = http.createServer((req, res) => {
    //To show which kind of data we are showing to the user
    // res.setHeader("Content-Type", "text/html");
    // res.statusCode = 404
    // res.statusMessage = "BAD"
    // shorthand for status (code, message, header)
    res.writeHead(202, "Good",{"Content-Type":"text/html"})
    res.write("<h1>Hello from node.js server</h1>");
})



//Listening on port 8000
server.listen(8000, () => console.log('Server up'))

http.createServer를 사용하여 서버를 생성한다. res.write를 통해 클라이언트에게 HTML을 전송할 수 있다. 상태 코드와 메세지, 그리고 헤더를 한 번에 설정하는 방법은 res.writeHead를 사용하는 것이다. 서버를 생성하는 것만으로는 충분하지 않으며, server.listen을 사용하여 포트 8000에서 서버가 요청을 받을 수 있게 해야 한다.

res.writeHead: 응답의 상태 코드, 상태 메세지, 그리고 헤더를 한 번에 설정할 수 있는 메서드
res.write: 응답 본문을 작성하는 메서드, 여기서는 간단한 HTML 코드를 작성하고 있다.
res.end:응답을 종료하는 메서드로, 응답이 완료되었음을 클라이언트에게 알린다.
server.listen:서버가 지정된 포트에서 요청을 듣기 시작하게 한다. 여기서는 포트 8000을 사용하였다.

Routing

HTTP 모듈을 이용해 라우팅 하는 방법을 알아보자. 대부분 Express를 이용하기 때문에 잘 사용하지 않지만, 기본 개념을 이해하는 것이 중요하다.

import http from 'http'

const server = http.createServer((req,res) => {
    if(req.url === '/'){
        res.writeHead(200, "OK",{"Content-Type" : "text/html"})
        res.end("<a href= '/contact'>contact page</a>")
    } else if (req.url === '/about'){
        res.writeHead(200, "OK",{"Content-Type" : "text/html"})
        res.end("<h2>About section</h2>")
    } else if (req.url === '/contact'){
        res.writeHead(200, "OK",{"Content-Type" : "text/html"})
        res.end("<h3>Contact</h3>");
    } else {
        res.writeHead(404, "BAD",{"Content-Type" : "text/html"})
        res.end("<h1>404 page not found</h1>")
    }
})



server.listen(8000,() => console.log("server up!"))

위의 코드처럼 res.writeHead()로 각각의 상태 코드를 설정하고, res.end()로 보여주고 싶은 내용을 작성한다. res.end()를 사용하는 이유는 자원을 낭비하지 않기 위해서로, 응답을 마치고 서버가 더 이상 해당 요청에 대해 작업을 수행하지 않도록 하기 위함이다.

Serving pages

public 폴더를 만들어서 그 안에 about.html과 home.html 파일을 넣고, 해당 파일들을 서빙하는 방법을 알아보자.

//how to serve about and home html on here ?
import http from 'http';
import fs from "fs";

const server = http.createServer((req, res) => {
    if(req.url === '/'){
        res.writeHead(200, "OK", {"Content-Type" : "text/html"})
        fs.readFile("./public/home.html", (error, data) => {
            if(error) throw error;
            res.end(data)
        })
    }else if(req.url === '/about'){
        res.writeHead(200, "OK", {"Content-Type" : "text/html"})
        fs.readFile("./public/about.html", (error, data) => {
            if(error) throw error;
            res.end(data)
        })
    }else {
        res.writeHead(400, "BAD", {"Content-Type" : "text/html"});
        res.end("<h3>404 page not found</h3>")

    }
})

server.listen(8000, () => console.log('server up!'))

writeHead()를 이용해 상태 코드를 설정하는 것은 이전과 동일하며, readFile()을 이용해 렌더링할 파일을 불러온다. 두 번째 인자로 에러 처리를 해주는데, 에러가 발생하면 에러를 throw 하고, 그렇지 않으면 불러온 데이터를 응답으로 전송한다.(불러온 파일이 데이터)

0개의 댓글