아주 간단한 Node.js express 만들기

회사에서 Dockerfile에 올릴 테스트 코드를 작성하기 위해, 기본 Node.js express를 만들어야 하는 상황이 생겼다.

 

간단한 node.js express 환경을 만들어보자.
(로컬에 node.js와 npm이 설치 되어 있어야 한다.)

1. 새로운 폴더 하나 생성 후 터미널에서 기본 세팅

# node app의 초기 설정
npm init 
# express 설치 
# package.json에 dependency 정보가 저장되어 있어야 docker 환경에서 실행 가능함으로 반드시 --save를 써줄 것
npm install express --save


2. index.js 파일을 추가해준다.

// [index.js]

// Importing the required modules
const express = require('express');

// Creating an instance of express
const app = express();

// port number is 8000
const port = 8000

// Defining a route for handling requests to the root URL
app.get('/', (req, res) => {
    res.send('Hello World!');
});

// Starting the server and listening on a port
app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
});

 

3. 서버를 실행한 뒤 localhost:8000에 접속해서 'Hello World!'가 잘 찍히는지 확인한다.

# 서버 실행 
node index.js