[Node JS] express tutorial / 시작하기

Onam Kwon·2022년 3월 27일
0

Node JS

목록 보기
1/25

What is

Node JS

Node JS란 JavaScript의 runtime으로 자바스크립트가 돌아가는 환경을 말하며 웹 브라우저 외의 영역인 서버측에서 자바스크립트 언어를 사용 할 수 있게 해준다.
자바스크립트 라는 언어는 원래 브라우저에서만 돌아갈 수 있었다.

V8

각 브라우저별로 엔진이 존재하며, Chrome: V8, IE: Chakra, Firefox: Spider monkey, Safari: JavaScriptCore등이 존재한다.
여기서 크롬 브라우저의 V8 엔진이 Node JS에 들어가있고, 엔진의 역할은 자바스크립트 언어를 기계어로 해석하는 역할을 한다.

express

Node JS의 express라는 framework를 사용해 서버를 쉽게 구현할 수 있다.

References:

  1. https://stackoverflow.com/questions/42616120/what-is-the-relationship-between-node-js-and-v8
  2. https://nodejs.dev/learn/the-v8-javascript-engine

0. 폴더 생성

Node JS express를 이용해 서버를 구축할 적당한 폴더를 하나 만든다.

1. package.json

Node JS를 사용하는 프로젝트는 package.json이라는 파일을 만들게 된다.
package.json파일의 역할은 현재 이 프로젝트에서 사용하는 패키지들의 정보 및 프로젝트 이름, 설명, 그리고 작성자를 나타낸다.
인간과 기계의 가독성을 위해 package.json파일은 항상 JSON형식을 사용한다.

package.json파일 예시▼

터미널에서 아래 코드를 입력한 후 엔터를 눌러 확인과정을 거쳐준다.

npm init

엔터를 누르며 진행을 마친 후 마지막에 재확인으로 y를 누르면 tutorial폴더에 package.json파일이 생성된 것을 확인 할 수 있다.

2. install express

아래의 명령어를 이용해 package.json파일에 express모듈을 설치해 줄 수 있다.

npm install express --save

맨 처음 package.json파일과 비교했을때, 맨 마지막 부분에 dependencies항목이 추가된 것을 확인 할 수 있다.

명령어를 실행하고 난 후 현재 경로에서 파일 목록을 확인하면 package.json, package-lock.json 그리고 node_modules파일이 생긴걸 확인할 수 있다.

package-lock.jsoon파일과 node_modules파일은 나중에 따로 다루도록 하겠다.

3. express 사용하기

현재 경로에 index.js파일을 만든 후 아래 코드를 사용해 준다.

// importing express module that was installed previously.
const express = require('express');
// declaring an app using the express framework module.
const app = express();

// declaring port number. You can use this number whatever you want.
const port = 8080;
// this middleware allows to start server using port number 8080
app.listen(port, function() {
    console.log('Listening on '+port);
});

// This middleware is executed when there is a get request with '/' path.
// web browser would show this message when this middleware is executed.
app.get("/", function (req, res) {
    res.send("Hello World!");
});

설치했던 express 프레임워크를 가져와준다.

const express = require('express');    

express 프레임워크의 반환값을 app에 넣어준다.

const app = express();

port번호를 선언해 준다. port에 관해선 다음에 더 알아보도록 하겠다.

const port = 8080;

위에서 선언해준 port를 인자로 넘겨준 후 서버가 문제없이 열리면 해당 문구가 출력된다.

app.listen(port, function() {
    console.log('Listening on '+port);
});

'/' 경로의 get요청이 들어올 때 마다 이 미들웨어가 실행된다. 클라이언트는 브라우저에서 인사 메시지를 확인할 수 있다.

app.get("/", function (req, res) {
    res.send("Hello World!");
});

위 코드를 전부 입력했다면 저장을 한 후 본인의 터미널(커맨드라인)에 아래 명령어를 실행시켜준다.
실행하기전 저장하는걸 까먹지 말도록 하자!
만약 파일 이름을 index.js가 아닌 다른 파일로 했다면 해당 파일 이름으로 실행시켜 주면 된다.

node index.js

서버 파일을 실행 한 후 브라우저의 http://localhost:8080로 이동하면 세상과 인사하는 메시지가 전달되었음을 확인할 수 있다.

profile
권오남 / Onam Kwon

0개의 댓글