Node.js의 생산성을 극대화 하기 위해 프레임워크를 설치해보려고 합니다. 그 중 가장 대표적인 Node.js의 프레임워크인 express를 설치하는 방법을 설명하겠습니다.


먼저 폴더 하나를 만들고 터미널을 만든 폴더 경로로 이동합니다. 

터미널에 아래와 같이 입력합니다.npm init을 입력하면 여러가지 묻게 되는데 가볍게 엔터를 연타합니다. 

그러면 아래와 같이 엔터 친 내용들이 나오면서 package.json 파일이 설치가 될겁니다.

(http://expressjs.com/en/starter/installing.html)

$ npm init


..생략..


{ "name": "test", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" }

package.json 파일이 설치된게 확인이 되면 터미널에서 npm을 통해 express를 설치하도록 합니다.

$ npm install express --save

설치가 끝나고 폴더를 확인해보면 node_module폴더와 package.json 파일이 있습니다.


설치가 끝나면 웹서버 파일을 하나 만들고 브라우저에 hello world를 찍어보도록 하겠습니다.

app.js로 파일을 만들고 아래와 같은 소스코드를 넣고 저장해보겠습니다.

http://expressjs.com/en/starter/hello-world.html )

var express = require('express');
var app = express();

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

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});


이제 app.js 를 실행해보겠습니다.

node app.js

Example app listening at http://:::3000

브라우저로 localhost:3000으로 들어가보면 hello world 가 찍히는게 보입니다. 

node_module에 들어가게 되면 express 모듈을 확인할 수 있습니다. require('express')를 통해서 express 모듈을 불러오게 되고 express를 통해 웹서버를 실행하는 예제를 해봤습니다.


반응형

Node.js는 apache와 다르게 특정 경로에서 설정과 소스코드를 수정하는게 아니라 내가 만든 경로에 모듈과 설정, 소스코드들을 위치하고 서버를 실행하게 됩니다.


먼저 폴더를 하나 만들고 그 안에 app.js 라는 이름으로 자바스크립트 파일을 하나 만듭니다.

그리고 app.js에 서버가 될 수 있도록 소스코드를 넣도록 하겠습니다. 

https://nodejs.org/en/about/

const http = require('http');

const hostname = '127.0.0.1';
const port = 1337;

http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello World\n');
}).listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
app.js 파일을 저장하고 실행해보겠습니다.

폴더 경로로 이동하고 node app.js 를 입력합니다.

아래와 같이 서버가 실행 됐다고 하면 정상 작동 중입니다. 

$ node app.js

Server running at http://127.0.0.1:1337/

브라우저를 키고 http://127.0.0.1:1337/ 를 입력하면 Hello World 라고 나오는걸 확인할 수 있습니다.


만약 포트를 80포트로 설정할 경우 아래와 같은 에러를 출력하게 됩니다.

events.js:141

      throw er; // Unhandled 'error' event

      ^

Error: listen EACCES 127.0.0.1:80

    at Object.exports._errnoException (util.js:874:11)

    at exports._exceptionWithHostPort (util.js:897:20)

    at Server._listen2 (net.js:1221:19)

    at listen (net.js:1270:10)

    at net.js:1379:9

    at doNTCallback3 (node.js:452:9)

    at process._tickCallback (node.js:358:17)

    at Function.Module.runMain (module.js:469:11)

    at startup (node.js:136:18)

    at node.js:963:3

그럴 땐 sudo 를 붙여서 실행하면 정상 작동합니다.

$ sudo node app.js


반응형

저는 AWS EC2에 ubuntu를 설치했습니다. 그래서 ubuntu에서 node 설치하는 방법과 개발하는 방법을 작성하려 합니다.

먼저 Node.js 홈페이지에 가서 DOWNLOADS (https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions)에서 아래 코드를 복사합니다.

curl -sL https://deb.nodesource.com/setup_5.x | sudo -E bash -
sudo apt-get install -y nodejs
sudo apt-get install -y build-essential

터미널을 열어서 실행하게 되면 설치가 끝납니다. 제대로 설치가 됐는지 확인하기 위해서 node -v 라고 입력하면 아래와 같이 버전 정보가 나오면 잘 설치되었습니다.

$ node -v
$ v5.2.0

node 설치가 끝나면 npm을 설치해야 합니다.  

npm(https://www.npmjs.com/) 은 Node Packaged Modules 로써 필요한 node 모듈들을 설치하는 패키지 매니저입니다. (a package manage for JavaScript)

$ sudo apt-get install npm
이제 다 설치가 끝났습니다. 

모든 프로그래밍의 시작인 hello world를 실행해보도록 하겠습니다.

원하는 경로로 이동 후 hello.js 파일을 만들고 그 안에 내용을 넣고 저장을 합니다.

console.log('hello world');

이제 터미널을 키고 hello.js를 실행시킵니다.

$ node hello.js

hello world

hello world 가 출력되면 끝. 

파일을 직접 안만들고 바로 테스트 할 수도 있습니다. 

$ node

> console.log('hello world');

hello world

undefined

실행된 node를 종료하는 방법은 ctrl + c를 2번 누르면 종료하게 됩니다.


반응형

+ Recent posts