01. Node js 기반 Web server

2021. 10. 10. 14:20Web dev

Node js web server를 구축해보겠습니다.

현재 단계에서는 localhost에서 실행 가능하며,

검색을 통해 얻은 지식이므로 정석적인 방법이 아닐 수 있습니다!

 

1. 관련 프로그램을 설치합니다.

 - Node js LTS version

   - LTS 버전을 다운받아주세요.

   - LTS는 안정적인 버전을 뜻합니다. 새로운 버전은 에러가 존재할 수 있으니까요

https://nodejs.org/ko/

 

Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

 - VSCode

    - extension은 취향 껏 골라서 사용하시면 됩니다.

https://code.visualstudio.com/download

 

Download Visual Studio Code - Mac, Linux, Windows

Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows. Download Visual Studio Code to experience a redefined code editor, optimized for building and debugging modern web and cloud applications.

code.visualstudio.com

 

2. 원하는 곳에 폴더를 만들고, VSCode에서 폴더열기로 해당 폴더를 열어 줍시다.

  - 폴더이름은 http_server로 지었습니다.

 

3. node.js command를 실행시켜 줍니다.

아래부터 $ 표시는 명령어 한줄을 의미합니다!

$ cd [현재 생성한 폴더 디렉토리]

$ npm init
// 입력창이 여러개 뜰텐데 그냥 엔터 연타 해주시면 됩니다!

$ npm install express

$ npm install -g nodemon
// 이건 밑에서 설명합니다!

 


 

4. 아래의 구조에 맞춰 코드파일을 생성합니다. (단축키는 CTRL + N)

  - http_server/server.js

  - http_server/public/index.html

  - http_server/public/js/script.js

  - http_server/public/css/style.css      // 저는 사용 안하지만 express 구조에서는 이게 정석이라고 하더라구요.

 

5. server.js 코드 작성

// server.js

const path = require('path');
var express = require('express');
var app = express();

const DIR = path.join(__dirname, '/public/');
app.use(express.static(DIR));

app.listen(3000, function () {
    console.log("start! express server on port 3000")
})

  - require

    - java의 import, C계열 언어의 #include와 같습니다.

  - const DIR = path.join(__dirname, '/public/');

    - __dirname : 현재 server.js가 있는 폴더 경로

    - path.join() : 첫 번째 인자와 두번째 인자의 문자열을 이어줍니다.
  - app.use(express.static(DIR));

    - node 실행할 디렉토리가 'http_server' 이므로, public 폴더도 있다고 알려줍니다.

  - app.listen(3000, function () { } )

    - 3000번 포트로 서버를 열어줍니다.

    - 여기서 포트번호는 변경 가능한데, 몇몇 포트는 이미 점유중인 포트일 수 있습니다.

 

6. index.html 작성

- 각종 태그들은 직접 검색해보시는 게 이해가 더 빠를 거 같습니다.

- script defer src="your_js_path" 태그는 백엔드 쪽 코드가 있음을 알려주는 부분입니다.

  - 많은 예제들이 html 하나에 작성되어 있는 경우가 있는데, <script> </script> 부분의 내용을 js 파일에 그대로 옮기고 해당 경로를 위와 같이 경로로 알려주면 됩니다.

- 심플하게 타이틀 하나, 버튼 하나 달아보았습니다.

// index.html

<!DOCTYPE html>
<html>

<head>
    <title>Main page</title>

    <script defer src="/js/script.js"></script>

    <style>
        body {
            text-align: center;
        }

        form {
            display: block;
            border: 1px solid black;
            padding: 20px;
        }
    </style>
</head>

<body>
    <h1>Node.js Server</h1>
        <input type="button" id="btn" value="버튼">
    </form>
</body>

</html

 


 

7. 코드 실행

- cd : change directory

- nodemon

  - npm 키워드로 실행시키면 소스코드가 변경될 때마다 npm 키워드로 재실행시켜주어야 합니다.

  - nodemon을 사용하고, 코드 수정 후 편집기에서 server.js에서 ctrl+s를 눌러 저장을 누르면 알아서 갱신시켜 줍니다.

    - 다른 파일 수정 후에도 server.js에서 ctrl+s를 눌러줘야 합니다.

$ cd http_server // your_http_server_directory
$ nodemon server.js

'Web dev' 카테고리의 다른 글

##. Https 인증서 받기(무료!)  (0) 2021.10.10
02. Node js POST 통신 예제  (0) 2021.10.10