Express 가 4.x 이 되면서 Connect 라이브러리를 사용하지 않는다. 프로젝트 생성시에도 body-parser, cookie-parser 를 추가로 설치 해줘야 한다.


파일 업로드 하는 부분에 있어서도 별도의 미들웨어를 사용해야 한다. 간단하게 사용할 수 있는 Multer 를 소개 한다.



설치 시 --save 옵션을 사용하게 되면 package.json 에 추가되어 다른 환경에 설치 시 npm install -d 로 일괄 설치 할 수 있다.


$ npm install multer --save


app.js 에 미들웨어 선언을 하자.


var app = express()
app.use(multer({ dest: './uploads/'}))


파일 업로드 시 아래의 객체에서 확인이 가능 하다.


console.log(req.body)
console.log(req.files)


자세한 내용은 github 를 참조 하도록 하자.



app.js 파일 중 일부

// ..
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.cookieParser());
app.use(express.bodyParser());
// ..

log 파일 중 일부

GET / 200 119ms - 505b

GET /stylesheets/style.css 304 27ms


log를 좀더 자세히 보고 싶은 경우

app.use(express.logger({ format: ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"' }));


format 설정을 위와 같이 넣어 준다.

192.168.0.xx - - [Thu, 01 Aug 2013 01:53:19 GMT] "GET / HTTP/1.1" 200 505 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36"


위와 같이 상세하게 정보를 볼 수 있다.




Nodejs, npm 은 설치 되어 있다고 가정 한다.


Step 1.  express 설치 하기

-g 옵션을 주게 되면 전역으로 설치 된다.


whitelife@whitelife:~/work$ sudo npm install -g express


Step 2.  프로젝트 생성 하기

생성하기 전에 도움말부터 보자.


whitelife@whitelife:~/work$ express --help


Usage: express [options]


  Options:


    -h, --help          output usage information

    -V, --version       output the version number

    -s, --sessions      add session support

    -e, --ejs           add ejs engine support (defaults to jade)

    -J, --jshtml        add jshtml engine support (defaults to jade)

    -H, --hogan         add hogan.js engine support

    -c, --css <engine>  add stylesheet <engine> support (less|stylus) (defaults to plain css)

    -f, --force         force on non-empty directory


참고해야 하는 옵션은 보통 view, session 추가 설정 부분 이다. 

이제 프로젝트를 생성해 보자.

view engine 은 따로 설정을 하지 않으면 jade로 설정 된다.


whitelife@whitelife:~/work$ express -s -e whitelife


   create : whitelife

   create : whitelife/package.json

   create : whitelife/app.js

   create : whitelife/public

   create : whitelife/public/javascripts

   create : whitelife/public/images

   create : whitelife/public/stylesheets

   create : whitelife/public/stylesheets/style.css

   create : whitelife/views

   create : whitelife/views/index.ejs

   create : whitelife/routes

   create : whitelife/routes/index.js

   create : whitelife/routes/user.js


   install dependencies:

     $ cd whitelife && npm install


   run the app:

     $ node app


whitelife@whitelife:~/work$ 


Step 3.  의존성 모듈 설치 하기

프로젝트에 대한 정의는 package.json을 참고 하자. 생성한 프로젝트 디덱토리를 보면 찾을 수 있다.


whitelife@whitelife:~/work/whitelife$ ll

합계 28

drwxr-xr-x  5 whitelife whitelife 4096  5월  3 11:24 ./

drwxrwxr-x 25 whitelife whitelife 4096  5월  3 11:24 ../

-rw-rw-r--  1 whitelife whitelife  937  5월  3 11:24 app.js

-rw-rw-r--  1 whitelife whitelife  181  5월  3 11:24 package.json

drwxr-xr-x  5 whitelife whitelife 4096  5월  3 11:24 public/

drwxr-xr-x  2 whitelife whitelife 4096  5월  3 11:24 routes/

drwxr-xr-x  2 whitelife whitelife 4096  5월  3 11:24 views/

whitelife@whitelife:~/work/whitelife$ vim package.json 


package.json

{

  "name": "application-name",

  "version": "0.0.1",

  "private": true,

  "scripts": {

    "start": "node app"

  },  

  "dependencies": {

    "express": "3.1.0",

    "ejs": "*" 

  }

}


npm을 이용하여 의존성 모듈을 설치하는데 위 dependencies 속성을 메타 정보로 활용 한다.

java 진영의 소스 관리 툴 maven 과 흡사하다고 생각 하면 된다.

이제 의존성 모듈을 설치 하자.


whitelife@whitelife:~/work/whitelife$ npm install -d

npm info it worked if it ends with ok

npm info using npm@1.2.18

npm info using node@v0.10.5

npm WARN package.json application-name@0.0.1 No README.md file found!

npm info preinstall application-name@0.0.1

npm info trying registry request attempt 1 at 11:32:05

npm http GET https://registry.npmjs.org/ejs

npm info trying registry request attempt 1 at 11:32:05


// ...... ing

ejs@0.8.3 node_modules/ejs

express@3.1.0 node_modules/express
├── methods@0.0.1
├── fresh@0.1.0
├── range-parser@0.0.4
├── cookie-signature@0.0.1
├── buffer-crc32@0.1.1
├── cookie@0.0.5
├── commander@0.6.1
├── debug@0.7.2
├── mkdirp@0.3.3
├── send@0.1.0 (mime@1.2.6)
└── connect@2.7.2 (pause@0.0.1, bytes@0.1.0, formidable@1.0.11, qs@0.5.1)
npm info ok 


설치가 완료되면 의존성 모듈의 구조를 볼 수 있다.

심심할 때 마다 보다보면 좋은 모듈도 많다. mkdirp 를 여기서 보다가 참고해서 사용하고 있다.~ 


따로 모듈을 추가해야 할 경우 --save 옵션을 주면 package.json 에 같이 적용 된다.

whitelife@whitelife:~/work/whitelife$ npm install --save super

whitelife@whitelife:~/work/whitelife$ vim package.json 


// ...

"dependencies": {

  "express": "3.1.0",

  "ejs": "*" 

  "super": "~0.2.1" 

}

// ...


위와 같이 적용 한다면 해당 프로젝트를 다른 PC에 셋팅을 해야 한다고 해도 npm install -d 로 한번에 의존성 모듈 설치가 완료 된다. 


Step 4.  프로젝트 실행 하기

app.js 가 express의 설정 파일이라고 생각 하면 된다. 실행 해보자.


whitelife@whitelife:~/work/whitelife$ node app.js 

Express server listening on port 3000


브라우저를 띄워서 확인 하자.



여기까지 같이 왔다면 성공이다.~ 


※ 참고 사이트: http://expressjs.com/


+ Recent posts