Node.js, express 서버 띄우기

Chris·2019년 10월 1일
0

node.js를 설치하기

https://nodejs.org/ko/에서 LTS 버전을 다운로드하여 설치한다.

node.js와 npm 설치확인

NPM이란 node.js의 패키지 매니저이며, nodejs에서 사용하는 모듈이나 패키지를 설치, 관리한다.

$ node --version
$ npm --version	// npm 설치 확인

프로젝트 폴더 생성과 구조

$ mkdir nodejs	// 프로젝트 폴더 생성

project

nodejs
|- package.json
|- server.js
|- /views
   |-- index.html
   |-- about.html

package.json 생성

package.json에는 패키지에 관한 정보와 의존중인 모듈이나 패키지의 정보가 담긴다.

$ npm init

express 모듈 설치

$ npm install -g express --save
$ npm i express			// install 대신 i로 쓸 수 있음
$ cd [local path]/project		
$ npm link express		// express 글로벌 설치 후 프로젝트폴더로 가져옴

node.js 서버 생성

/server.js

var http = require('http')
var fs = require('fs')
var url = require('url')

http.createServer( (request, response) => {
    
    var pathname = url.parse(request.url).pathname

    console.log('pathname: ' + pathname)
	
  	// pathname으로 router 분기함 
    if (pathname == '/') {
        pathname = '/views/index.html'
    } else if (pathname == '/about') {
        pathname = '/views/about.html'
    }

    fs.readFile(pathname.substr(1), (err, data) => {
        if (err) {
            console.log(err)
            response.writeHead(404, {'Content-Type': 'text/html'})
        } else {
            response.writeHead(200, {'Content-Type': 'text/html'})
            response.write(data.toString())
        }
        response.end()
    })
}).listen(8081)

console.log('Server running at http://127.0.01:8081')

/views/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Main</title>
</head>
<body>
    Hey, this is index page
</body>
</html>

/views/about.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>About</title>
</head>
<body>
About...
</body>
</html>

node.js 서버 띄우기

$  server.js

http://127.0.01:8081/이나 http://127.0.01:8081/about으로 접속하여 확인 가능하다.

관련 링크
https://velopert.com/379
https://velopert.com/294
https://jeong-pro.tistory.com/65
https://www.zerocho.com/category/NodeJS/post/578c64621e3613150037d3b3
https://skout90.github.io/2017/08/15/Node.js/4.%20%ED%85%9C%ED%94%8C%EB%A6%BF%EC%97%94%EC%A7%84/

profile
올드보이 코더

1개의 댓글