블로그 이미지
윤영식
Full Stacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

2013. 5. 7. 09:37 NodeJS/Concept

서비스 또는 솔루션을 만들기 위해 Node.js와 Express.js를 선택하였다면  그 다음 고민은 애플리케이션 개발을 위하여 필요한 스택을 선정하는 일이다. 크게는 로깅, 환경설정, 통신등 기본적인 부분들을 직접 개발하지 말고 이미 만들어진 바퀴를 공짜로 구해서 달아보자 



1. 준비하기 

  - Programming Javascript Application Book 책의 내용을 발췌한 것이다 

  - Node 버전관리 NVM 설치 

    + https://github.com/creationix/nvm

    + 설치 : nvm install [버전]

    + 수행 : nvm run [버전]

    + 확인 : nvm ls  (설치된 버전 목록을 보여줌)

    + 가능 : nvm ls-remote (설치 가능 버전 목록을 보여줌)

  - nvm 설치 명령 : git 사전 설치요구 : 수행시 nvm.sh 에 syntax오류가 나오면 nvm.sh을 copy하고 기존것 삭제후 다시 paste하여 만듦

$ curl https://raw.github.com/creationix/nvm/master/install.sh | sh


    + 기타 명령들 

$ nvm help


Node Version Manager


Usage:

    nvm help                          Show this message

    nvm install [-s] <version>  Download and install a <version>

    nvm uninstall <version>     Uninstall a version

    nvm use <version>           Modify PATH to use <version>

    nvm run <version> [<args>]  Run <version> with <args> as arguments

    nvm ls                            List installed versions

    nvm ls <version>             List versions matching a given description

    nvm ls-remote                 List remote versions available for install

    nvm deactivate                Undo effects of NVM on current shell

    nvm alias [<pattern>]      Show all aliases beginning with <pattern>

    nvm alias <name> <version>    Set an alias named <name> pointing to <version>

    nvm unalias <name>                Deletes the alias named <name>

    nvm copy-packages <version> Install global NPM packages contained in <version> to current version


Example:

    nvm install v0.4.12            Install a specific version number

    nvm use 0.2                    Use the latest available 0.2.x release

    nvm run 0.4.12 myApp.js   Run myApp.js using node v0.4.12

    nvm alias default 0.4        Auto use the latest installed v0.4.x version


  - 프로젝트 만들고 초기화 하기 

    + 디렉토리 만들고 해당 디렉토리로 이동

    + npm init 수행하여 package.json 파일 만들기 : 이름, 버전, 설명, 키워드, 저장소위치, 라이센스 및 기타 정보등을 입력한다 

$ mkdir basic && cd basic

$ npm init

This utility will walk you through creating a package.json file.

It only covers the most common items, and tries to guess sane defaults.


See `npm help json` for definitive documentation on these fields

and exactly what they do.


Use `npm install <pkg> --save` afterwards to install a package and

save it as a dependency in the package.json file.


Press ^C at any time to quit.

name: (basic) JavaScript-Programming

version: (0.0.0) 0.0.1

description: This is a javascript programming

entry point: (index.js)

test command: grunt test

git repository: https:/github.com/ysyun/javascriptacular

keywords: angularjs

author: yun dowon

license: (BSD) MIT

About to write to /Users/prototyping/express/basic/package.json:


{

  "name": "JavaScript-Programming",

  "version": "0.0.1",

  "description": "This is a javascript programming ",

  "main": "index.js",

  "scripts": {

    "test": "grunt test"

  },

  "repository": {

    "type": "git",

    "url": "https:/github.com/ysyun/javascriptacular"

  },

  "keywords": [

    "angularjs"

  ],

  "author": "yun dowon",

  "license": "MIT"

}



Is this ok? (yes)

npm WARN package.json JavaScript-Programming@0.0.1 No README.md file found!

$ ls -lart

-rw-r--r--  1 nulpulum  staff  360  5  7 09:22 package.json

drwxr-xr-x  3 nulpulum  staff  102  5  7 09:22 .


  - 모듈 설치시에 package.json 파일에 자동 기록을 위하여 npm install --save [module] 처럼 --save 옵션을 준다 



2. 준비할 스택들

  • Mout Like Underscore / LoDash. Stuff that should probably be included in JavaScript.

  • Express Web application framework.

  • Nconf Application config.

  • Hogan Mustache for express. (Jade 또는 EJS 를 써도 됨)

  • Superagent Communicate with APIs.

  • Socket.io Realtime communications (websockets).

  • Q Promises.

  • Async Asynchronous functional utilities.

  • Bunyan Logging. (Winston도 많이 사용)

  • Tape Testing. (Mocha, Karma 도 사용)

  • Cuid Better than guid/uuid for web applications.

  • Derby.js Add realtime, collaborative MVC to express. (Sails.js 또는 Bone.js 도 사용)

  • Node-http-proxy Proxy your service APIs.



3. Express 사용하기 

  - Routing 을 이용한다

  - Middleware를 통하여 중간에 Hooking 하여 처리하고 다음으로 next() 호출 넘기는 use 를 사용한다 

// Add some data to the request object that your other
// midleware and routes can use.
app.use(function (req, res, next) {
  req.foo = 'bar';
  next();

});

    + 전체 예제 

'use strict';
var express = require('express'),
 
  // Create app instance.
  app = express(),
 
  // Use the `PORT` environment variable, or port 44444
  port = process.env.PORT || 44444;
 
// The new middleware adds the property `foo` to the request
// object and sets it to 'bar'.
app.use(function (req, res, next) {
  req.foo = 'bar';
  next();
});
 
app.get('/', function (req, res) {
  res.setHeader('Content-Type', 'text/plain');
 
  // Send the value passed from the middleware, above.
  res.end(req.foo);
});
 
app.listen(port, function () {
  console.log('Listening on port ' + port);

});


// 결과 : use를 설정한 순서대로 처리된다 

$ curl http://localhost:44444/
bar



4. SailsJS

  - 난 sails를 Full Stack Server Side Data-Oriented API Framework 이라고 말하고 싶다.

  - Front-end 단이 SPA로 개발될 경우

  - Back-end를 API 서버로 확장함 

  - Node.js + Express.js + MongoDB 와 연결 및 JSON Memory DB 사용가능

    + sails-angularjs-yeoman 의 로그인 데모

    + sails-mongodb 연결

    + sails-redis 연결



<참조>

   - 원문 : Getting start with Node and Express 

   - middleware의 next() 사용법 : Node.js의 connect 이해하기

   - AngularJS와 MongoDB 연결 Bridge


posted by 윤영식