ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Node.js 기본] 서버의 동작 원리 및 함수
    Node.js/nodeJS 기본 2022. 12. 11. 15:50
    반응형

    [Node.js 기본] 서버의 동작 원리 및 함수

    서버의 동작 원리

     

      내가 이해한 서버의 동작 원리는 클라이언트가 url에 접속하면(request) 서버는 이를 감지하고 request에 대응하는 response를 제공한다. 이때 대응하는 response를 제공하기 위해 사용되는 것이 request(url)의 path, query string, fragment 부분이다. nodeJS의 경우를 예로 들자면, request.url을 url 모듈의 parse()를 통해 path, pathname, query 등으로 구분하고 if 조건문과 fs모듈을 통해 조건(path, query등)에 따라 미리 정의된 response(html, 혹은 임의로 작성한 template)를 제공한다.

     

    • nodeJS를 통해 특정 path, query string에 대응하는 response를 미리 준비해두는 것이라 이해하면 편하다.
    • 접속자의 ui 조작을 통해 url은 자동으로 변경되며(각 ui에 링크를 걸어두거나 query를 변경하도록 함), request이에 따른 request 요청이 발생한다.

     

    var http = require('http');
    var fs = require('fs');
    
    var app = http.createServer(function(request,response){
        var url = request.url;
        if(request.url == '/'){
          url = '/index.html';
        }
        if(request.url == '/favicon.ico'){
          return response.writeHead(404);
        }
        response.writeHead(200);
        response.end(fs.readFileSync(__dirname + url));
     
    });
    
    app.listen(3000);

     


      위 코드는 생활코딩 node.js 수업에서 기본 적인 서버 생성을 위해 사용된 코드이다. 이 코드에는 서버 조작을 위한 여러 모듈과 함수가 사용되는데 간단히 정리하면 아래와 같다.

     


    1. node.js의 함수인 require()를 통해 http, fs 모듈을 로드하고 변수에 할당한다.

     


    2. http 모듈의 createServer(callBack) 함수를 통해 app.listen에서 지정된 port에서 http 요청을 수신하고 파라미터로 주어진 callBack함수로 요청을 처리하는 http server를 생성한 뒤, app 변수에 할당한다. 이러한 callBack 함수는 클라이언트 접속으로부터 발생한 요청에 대한 정보를 담은 request 객체, 클라이언트에 응답을 보내는데 사용되는 정보를 담은 response 객체를 파라미터로 가지며 http 요청을 수신할 때 마다 호출된다.

     

    let http = require('http');
    
    let app = http.createServer((req, res) => {
    	res.end('server created!!')
    })
    
    app.listen(800);

    http://localhost:800 접속 결과



    2-1. createServer의 콜백함수의 파라미터인 request는 클라이언트 요청에 대한 정보를 담은 객체이다. request 객체가 가진 property와 method는 아래와 같다.

     

    property / method features
    method return a string that represents the HTTP method of the request like "GET", "POST"
    ex. if (incoming request === GET) return string "GET"
    headers a object that contains the name-value pairs of the headers of the request
    ex. "Content-Type", "Accept-Languague", ...
    url URL of the request
    on('data', callBack) a method that used to register a callback that will be called whenever a chunk of data is received in the request body
    on('end', callBack) a method that used to register a callback that will be called when the request body has been fully received

     

     

    2-2. request와 마찬가지로 response는 incoming request가 발생했을 시, 이에 대응해 서버에서 클라이언트로 전송하는 데이터를 담고 있는 객체이다. 클라이언트는 이러한 response에 담긴 데이터에 접근할 수 있고 이를 이용해 페이지를 업데이트 하거나 기타의 액션을 취할 수 있다. respons 객체가 가진 property와 method는 아래와 같다.

     

    property / method features
    statusCode specifies the HTTP status code of the response
    writeHead(status, header) specifies HTTP status code of the response by status parameter, and spacifies header object by name-value pairs of the headers of the response( header parameter is optional)
    ex. res.writeHead(200, { 'Content-Type': 'text/plain' })
    setHeader(name, value) set a header in the response
    write(data) a method that can be used to write data to the response body
    end(data) a method that can be used to end the response, and send it to the client

     

     

    3. fs는 node.js 런타임의 내장 모듈로서 운영체제의 파일 시스템과 상호작용하기 위한 api를 제공한다. fs 모듈은 파일을 읽기, 쓰기, 생성하기, 지우기 등을 위한 여러 property와 method를 제공하며 이는 다음 글에 정리하도록 하겠다. 생활코딩 강의자료에서 fs.readFileSync(dir)을 사용했는데 이는 동기적으로 dir 파라미터로 주어진 path 파일의 컨텐츠를 읽는데 사용되며 두번째 파라미터는 파일 인코딩 형식을 지정하거나 버퍼로 반환하도록 하는 옵셔널 파라미터이다

    /* fs.readFileSync('directory', { encoding : 'utf8' }) */

     

     

    기타 배경지식

    • __dirname은 node.js의 전역변수로서 현재 모듈이 설치된 디렉토리를 특정한다. 이는 읽기 전용 변수로서 변경하거나 재할당 할 수 없다.
    • url은 웹 페이지의 위치를 가리키는 문자열이다. 다음 글에서 fs와 함께 정리하도록 해야겠다.

     

    정리

      node.js를 통한 서버의 동작원리는

    1. 포트에 대응하는 서버 생성

    2. request 조건별 서버 제어

    3. response로 이루어진다.

      서버 생성의 경우 require() 을 통해 http 모듈을 로드한뒤 createServer(callback) 를 통해 이루어진다. 이때 callback 함수는 생성된 서버에 할당한 port에 http request가 발생할 때마다 호출되어 함수가 정의하고 있는 제어에 맞게 동작하며 클라이언트에게 response를 전달한다. requset.url을 통해서 조건별 response를 설정 가능하며 response.writeHead()를 통해 http status에 대한 응답이 가능하다. 프로젝트 디렉토리에 페이지별 양식을 저장해 두고 fs로 읽어 온뒤 response.end()로 클라이언트에게 해당 데이터를 전송한다면 보다 동적으로 페이지 생성이 가능하다.

    반응형

    댓글

Designed by Tistory.