don't stop believing

node js 설치 (on Windows) 본문

node js

node js 설치 (on Windows)

Tongchun 2019. 5. 20. 14:51

간단하게 html, css, javascript를 올려볼 node 서버가 필요했습니다.
Windows에 빠르게 설치해 보겠습니다.

아래 node js 페이지에서 Windows 설치 파일(msi)을 다운 받습니다.

https://nodejs.org/en/download/

 

Download | Node.js

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

nodejs.org

node-v10.15.3-x64.msi 파일을 다운 받았습니다. 버전은 10.15.3이네요.

 

다운받은 설치 파일을 더블 클릭해 설치를 시작합니다.

설치 과정은 오른쪽 이미지처럼 Destination Folder(설치 경로)와 Custom Setting 정도의 확인이며 저는 기본으로 설치해 줬습니다.

 

설치가 되었다면 Windows Command prompt (cmd)창을 열고 node js의 버전을 확인합니다.

C:\Users\tongchun>node -v
v8.11.3

node를 설치하면 npm도 같이 설치가 됩니다. npm(Node Package Manager)의 버전도 같이 확인해 줍니다.

C:\Users\tongchun>npm -v
5.6.0

node와 npm 버전을 확인했다면 이제 static files (html, css, javascript, images ...)을 실행할 서버를 실행해 보겠습니다.

node 서버를 실행하기 위해서는 많은 지식이 필요하지만 우리는 html 파일을 띄우는게 목적이므로 중요하지만 우리에게 필요하지 않은 지식은 넘어가겠습니다.

 

서버를 실행할 폴더를 만들어 줍니다. 저는 ngle 이라고 폴더를 만들었습니다.

(D:\node\server\ngle)

 

cmd창에서 ngle 폴더로 이동합니다. 그리고 아래 명령으로 package.json 파일을 초기화해 줍니다.

D:\node\server\ngle>npm init

npm init을 실행하면 몇가지 묻습니다.

package name: (ngle)
version: (1.0.0)
description:
entry point: (index.js) server.js
test command:
git repository:
keywords:
author:
license: (ISC)

저는 그냥 엔테 키를 누르고 기본 설정으로 했습니다. 기본 설정은 괄호(  ) 안의 내용이 들어갑니다.

entry point만 server.js로 했습니다.

 

설정이 완료되면 ngle 폴더안에 package.json 파일이 생성되고 설정한 값으로 작성되어 있습니다.

이번에는 express package를 설치할 차례입니다 express 는 node에서 손십게 웹서버를 만들어 주는 모듈입니다.

D:\node\server\ngle>npm install express --save

express를 설치하고 package.json을 다시 확인하면 dependencies 항목이 추가된 것을 확인할 수 있습니다.

이제 서버를 실행할 파일을 만들어 주겠습니다.

ngle 하위에 server.js 라고 파일을 만들어 줍니다. 그리고 아래와 같이 작성합니다.

const express = require('express');

const app = express();
const PORT = process.env.PORT = 8000;

app.use(express.static('public'));

app.listen(PORT, () => {
  console.log('Server is running at:',PORT);
});

서버 포트는 8000으로 설정했습니다. 그리고 public 폴더 안에있는 파일들을 static file로 인식하도록 지정했습니다.

app.use(express.static('public'));

ngle 폴더 밑에 public 폴더를 만들어 줍니다.

그리고 아래와 같이 html 파일을 만들어 줍니다. 저는 tongchun.html 로 만들어 줬습니다.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>tongchun</title>
    </head>
    <body>
        <p>node 서버 띄우는거 참 쉽죠?!</p>
    </body>
</html>

모든 준비는 완료되었습니다. 이제 server.js 파일을 node로 실행해 줍니다.

D:\node\server\ngle>node server.js

만약 아래와 같이 Windows 보안 경고가 실행되었다면 액세스 허용을 클릭해 줍니다.

브라우저를 열어 아래 url로 접속합니다.

http://localhost:8000/tongchun.html

localhost가 아닌 자신의 PC IP로 하면 다른 곳에서도 볼수 있습니다. 제 IP는 10.10.2.125입니다.

http://10.10.2.125:8000/tongchun.html

 

만약 html 등의 static 파일을 폴더로 구분해 주고 싶다면 public 하위에 폴더를 만들어 주면 됩니다.

public 폴더 밑에 test01폴더를 만들고 그 안에 america.html을 만들어 줬다면 http://10.10.2.125:8000/test01/america.html로 호출하면 됩니다.

 

Comments