wgnodejsstudy / nodejs

0 stars 1 forks source link

Node.js Basic #3

Open topgaren opened 5 years ago

topgaren commented 5 years ago

Node.js

1. 스크립트 실행 방법

1) 터미널에서 node 명령어를 입력하여 REPLRead Eval Pring Loop 실행.

$ node
> console.log('Hello Node.js!')
Hello Node.js!
undefined
>

2) 자바스크립트 파일을 실행.

/* HelloNodeJS.js */

var output = '';
for (var i = 0; i < 10; i++) {
    console.log(output += '*');
}
$ node HelloNodeJS.js
*
**
***
****
*****
******
*******
********
*********
**********

2. 웹 서버 생성 및 실행

웹 서버를 만들 때는 express라는 외부 모듈을 사용해아 하므로 다음 명령어로 express 모듈을 설치한다.

> npm install express

아래 코드는 기본적인 웹 서버(아무런 기능도 제공하지 않음)를 생성한다.

/* BasicServer.js */

// express 모듈을 추출한다.
var express = require('express');

// 웹 서버를 생성한다.
var app = express();

// 웹 서버를 실행한다.
app.listen(52273, function() {
    console.log('Server Running at http://127.0.0.1:52273');
});

포트 번호는 임의로 설정하였으며 49151 이상 원하는 숫자를 사용하면 안전하다.

  • 0번 ~ 1023번: 잘 알려진 포트 (well-known port)
  • 1024번 ~ 49151번: 등록된 포트 (registered port)
  • 49152번 ~ 65535번: 동적 포트 (dynamic port)
    
    $ node BasicServer.js
    Server Running at http://127.0.0.1:52273

### 3. app.use() 메서드와 미들웨어
웹 서버에 기능을 부여할 때는 `app.use()` 메서드를 사용한다. `app.use()` 메서드의 매개변수에는 콜백 함수를 넣을 수 있다. 사용자의 요청을 처리해주는 `app.use()` 메서드의 콜백 함수를 미들웨어<sup>Middleware</sup>라고 부른다.   

아래 코드는 사용자가 서버에 접속하면 자동으로 실행되는 `request` 이벤트 리스너를 미들웨어로 사용한 코드이다.
> 미들웨어는 위에서 아래로 실행되며, `request` 이벤트 리스너의 매개변수 `next`는 다음에 위치한 콜백 함수를 의미한다.
``` javascript
/* BasicServer.js */

// express 모듈을 추출한다.
var express = require('express');

// 웹 서버를 생성한다.
var app = express();

// 미들웨어 구성
app.use(function (request, response, next) {
    console.log('first');
    next();
});
app.use(function (request, response, next) {
    console.log('second');
    next();
});
app.use(function (request, response, next) {
    response.send('<h1>Hello Middleware!</h1>');
});

// 웹 서버를 실행한다.
app.listen(52273, function() {
    console.log('Server Running at http://127.0.0.1:52273');
});

서버를 실행하고 http://127.0.0.1:52273 에 접속했을 때의 결과

$ node BasicServer.js
Server Running at http://127.0.0.1:52273
first
second
first
second

middlewareBorder

3.1 정적 파일 제공

기본적인 스타일시트 파일과 자바스크립트 파일과 같이 아무리 요청해도 변하지 않는 파일을 정적 파일이라고 한다. static 미들웨어는 정적 파일을 제공할 때 사용하는 미들웨어이다.

현재 프로젝트 경로에 public 이라는 이름의 폴더를 생성하고 그 아래에 index.html 파일을 아래와 같이 생성한다.

<!DOCTYPE html>
<html>
<head>
    <title>node.js express</title>
</head>
<body>
    <h1>index.html</h1>
    <p>Lorem Ipsum is simply dummy text<!-- 글자 많이 입력. --></p>
    <p>Contrary to popular belief,<!-- 글자 많이 입력. --></p>
</body>
</html>

static 미들웨어를 활용하는 코드는 다음과 같다.

// express 모듈을 추출한다.
var express = require('express');

// 웹 서버를 생성한다.
var app = express();
app.use(express.static('public'));
app.use(function (request, response) {
    response.send('<h1>Hello Middleware!</h1>');
});

// 웹 서버를 실행한다.
app.listen(52273, function() {
    console.log('Server Running at http://127.0.0.1:52273');
});
$ node BasicServer.js
Server Running at http://127.0.0.1:52273
static

3.2 라우터

사용자의 요청에 따라 사용자가 필요한 정보를 제공하는 것을 "라우트Route한다"라고 표현한다. 이러한 기능을 수행하는 미들웨어를 라우터Router라고 부른다. router 미들웨어는 따로 설정하지 않아도 자동적으로 사용된다.

다음은 app.all() 메서드를 사용하는 예제이다.

// express 모듈을 추출한다.
var express = require('express');

// 웹 서버를 생성한다.
var app = express();
app.use(express.static('public'));

// 라우트한다.
app.all('/a', function (request, response) {
    response.send('<h1>Page A</h1>');
});
app.all('/b', function (request, response) {
    response.send('<h1>Page B</h1>');
});
app.all('/c', function (request, response) {
    response.send('<h1>Page C</h1>');
});

// 웹 서버를 실행한다.
app.listen(52273, function() {
    console.log('Server Running at http://127.0.0.1:52273');
});

Reference : 모던 웹을 위한 JavaScript jQuery 입문 3판, 윤인성, 한빛미디어, 2017