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

Publication

Category

Recent Post

2013. 1. 31. 16:34 NodeJS/Concept

Node.js 에서 Express를 사용하면서 일관된 축약 언어 컴파일러로 JavaScript 코딩은 CoffeeScript를 사용하고, HTML은 Jade를 사용하고 CSS는 Stylus를 사용할 때 가장 기본적인 뼈대가 되는 코드를 만들어 주는 프레임워크 Cham을 알아보자. 


1) Cham 설치하기 

  - Node.js 와 NPM, CoffeeScript는 기본 설치되어 있어야 한다 

  - git clone 으로 설치하기 

$ git clone https://github.com/conancat/cham.git

Cloning into 'cham'...

remote: Counting objects: 155, done.

remote: Compressing objects: 100% (103/103), done.

remote: Total 155 (delta 48), reused 142 (delta 35)

Receiving objects: 100% (155/155), 136.89 KiB | 59 KiB/s, done.

Resolving deltas: 100% (48/48), done.


  - Express, jade, stylus 설치하기 

  - 설치후 브라우져 호출 : http://localhost:3000/ 

//////////////////////////////////////

// 설치 

$ cd cham

$ npm install express

npm http GET https://registry.npmjs.org/express/2.4.3

npm http 200 https://registry.npmjs.org/express/2.4.3

... 중략 ...

npm http 200 https://registry.npmjs.org/formidable

express@2.4.3 node_modules\express

├── mime@1.2.9

├── qs@0.5.3

└── connect@1.9.2 (formidable@1.0.11)


$ npm install jade

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

... 중략 ...

npm http 200 https://registry.npmjs.org/commander/-/commander-0.6.1.tgz

jade@0.28.1 node_modules\jade

├── commander@0.6.1

├── mkdirp@0.3.4

└── coffee-script@1.4.0


$ npm install stylus -g

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

... 중략 ...

C:\Users\yuwonsystem01\AppData\Roaming\npm\stylus -> C:\Users\yuwonsystem01\AppD

ata\Roaming\npm\node_modules\stylus\bin\stylus

stylus@0.32.0 C:\Users\yuwonsystem01\AppData\Roaming\npm\node_modules\stylus

├── debug@0.7.0

├── mkdirp@0.3.4

└── cssom@0.2.5


$ npm install vows

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

npm http 200 https://registry.npmjs.org/vows

npm http GET https://registry.npmjs.org/vows/-/vows-0.7.0.tgz

... 중략 ...

npm http 200 https://registry.npmjs.org/diff/-/diff-1.0.4.tgz

vows@0.7.0 node_modules\vows

├── eyes@0.1.8

└── diff@1.0.4


///////////////////////////////////

// 실행하기 

$ node app

Express server listening on port 3000 in development mode



2) 구조파악하기 

  - root 폴더에 CakeFile이 존재하여 cake를 수행할 수 있다. (CoffeeScript 형태로 작성)

/////////////////////////////////////

// cake를 실행하면 사용법이 출력됨 

D:\git-nulpulum\cham>cake

Cakefile defines the following tasks:


cake watch             # Watches all Coffeescript(JS) and Stylus(CSS) files

cake watchJS         # Watches all coffeescript files for changes

cake watchCSS      # Watches all CSS files for changes

cake compileJS       # Compiles all Coffeescript files into JS

cake test                # Runs all tests

cake docs              # Create documentation using Docco


//////////////////////////////////////////////

// watch 하고 있는 원본 소스들을 볼 수 있다

// 원본 소스는 전부 src에 위치함

D:\git-nulpulum\cham>cake watch

15:10:11 - compiled src\lib\helpers.coffee

15:10:11 - compiled src\lib\module.coffee

15:10:11 - compiled src\lib\conf.coffee

15:10:11 - compiled src\test\testHelpers.coffee

15:10:11 - compiled src\public\js\plugins.coffee

15:10:11 - compiled src\app.coffee

15:10:11 - compiled src\test\example.test.coffee

15:10:11 - compiled src\lib\routes.coffee

15:10:11 - compiled src\public\js\script.coffee

  watching C:\Users\yuwonsystem01\AppData\Roaming\npm\node_modules\stylus\lib\functions\index.styl

  watching src\public\css\conf\base.styl

  watching src\public\css\conf\helpers.styl

  watching src\public\css\conf\colors.styl

  watching src\public\css\elems\reset.styl

  watching src\public\css\elems\helpers.styl

  watching src\public\css\elems\typography.styl

  watching src\public\css\elems\common.styl

  watching src\public\css\pages\layout.styl

  watching src\public\css\pages\index.styl

  watching src\public\css\media\media.styl

  compiled public\css\style.css

  watching src\public\css\style.styl

15:15:16 - compiled src\app.coffee       <== app.coffee 를 열어서 살짝 수정하였더니 자동으로 재컴파일 됨 


  - 의존관계 파악을 위해 package.json 파일을 열어보자 

{

  "name": "cham",

  "version": "0.0.1",

  "private": true,

  "dependencies": {

    "express": "2.4.3",

    "jade": ">= 0.0.1"

  },

  "devDependencies": {

    "vows": ">= 0.5.9",     // BDD 테스트

    "stylus": ">= 0.13.9",  // CSS

    "coffee-script": ">= 1.1.2" // Javascript 

  },

  "engines": {

    "node": "*"

  },

  "author": "Grey Ang <conancat@gmail.com> (http://grey-ang.com)",

  "description": "Boilerplate for quick Coffeescript driven app, backed by Jade and Stylus",

  "repository": {

    "type": "git",

    "url": "git://github.com/conancat/cham.git"

  },

  "scripts": {

    "test": "cake test"

  }

}


  - CoffeeScript 문법의 CakeFile : "task <명칭>, <설명>, -> 펑션"  task 다음에 3개의 아규먼트로 cake task 만듦

    + watchJS 명령 : coffee -cw -o ./ src/

    + watchCSS 명령 : stylus --watch --include ./public --out ./public/css ./src/public/css

    + compileJS 명령 : coffee -c -o ./ src/

    + test 명령 : vows test/*.test.js

    + docs 명령

       docco src/*.coffee

       docco src/lib/*.coffee

       docco src/test/*.coffee 

//////////////////////////////////////////
// CakeFile 내역 
# Module requires
{spawn, exec} = require 'child_process'
sys = require 'sys'

# ## Helpers

# Helper function for showing error messages if anyting happens
printOutput = (process) ->
  process.stdout.on 'data', (data) -> sys.print data
  process.stderr.on 'data', (data) -> sys.print data
  
# Watch Javascript for changes
watchJS = ->
  coffee = exec 'coffee -cw -o ./ src/'
  printOutput(coffee)

# Watch CSS for changes
watchCSS = ->
  
  # Without Nib
  stylus = exec 'stylus --watch --include ./public --out ./public/css ./src/public/css'
  
  # Use this line instead if you're using Nib
  # stylus = exec 'stylus --watch --include ./public --use ./node_modules/nib/lib/nib.js --out ./public/css ./src/public/css'
  
  printOutput(stylus)
  
# ## Tasks
# I guess pretty self explainory? lol
task 'watch', 'Watches all Coffeescript(JS) and Stylus(CSS) files', ->
  watchJS()
  watchCSS()

task 'watchJS', 'Watches all coffeescript files for changes', ->
  watchJS()
  
task 'watchCSS', 'Watches all CSS files for changes', ->
  watchCSS()
  
task 'compileJS', 'Compiles all Coffeescript files into JS', ->
 coffee = exec "coffee -c -o ./ src/"
 printOutput(coffee)
  
task 'test', 'Runs all tests', ->
  vows = exec 'vows test/*.test.js'
  printOutput(vows)
  
task 'docs', 'Create documentation using Docco', ->
  docco = exec """
    docco src/*.coffee
    docco src/lib/*.coffee
    docco src/test/*.coffee
  """
  printOutput(docco)



3) 사용한 모듈들 알아보기

  - Stylus

    + CSS를 축약해서 표현, 사용이 간단하고, 코드가 간결해짐 

    + ; 과 { } 를 사용할 필요가 없고  DRY (Don't Repeat Yourself) 지원


  - Docco

    + 주석을 MarkDown 으로 줄 수 있다 (GitHub README.md 만들기와 일관성 있어 좋군)

    + 수행한 위치 바로 밑에 docs 폴더에 위치함 

    + 설치 : npm install -g docco

    + 수행 : docco src/*.coffee


  - Jade

    + HTML 템플릿 엔진 : 이것도 < > 사용이 필요없어 코드가 간결해짐

    + 사용 설명


  - Vows

    + 비동기 BDD for Node

//////////////////////////////////////////
// vowtest.js
var vows = require('vows'),
    assert = require('assert');

// Create a Test Suite
vows.describe('Division by Zero').addBatch({
    'when dividing a number by zero': {
        topic: function () { return 42 / 0 },

        'we get Infinity': function (topic) {
            assert.equal (topic, Infinity);
        }
    },
    'but when dividing zero by zero': {
        topic: function () { return 0 / 0 },

        'we get a value which': {
            'is not a number': function (topic) {
                assert.isNaN (topic);
            },
            'is not equal to itself': function (topic) {
                assert.notEqual (topic, topic);
            }
        }
    }
}).run(); // Run it 

///////////////////////////////////////

// 결과 : 성공 

D:\git-nulpulum\cham>node vowtest.js

··· ✓ OK » 3 honored (0.036s)



  - Express

    + 설치 : npm install -g express

    + 수행 : $ express <projectName>

//////////////////////////////////////////
// Express로 Listen Server 구성
var express = require('express');
var app = express();

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

app.listen(3000);


  - CoffeeScript

    + 설치 : npm install -g coffee-script

    + 실행 : coffee <파일명>.coffee    <== .coffee 확장자 생략가능   



<참조> 

  - https://github.com/conancat/cham

'NodeJS > Concept' 카테고리의 다른 글

[Node.js] Express의 Connect 살펴보기  (0) 2013.03.11
[Node.js] 기술 발전 방향 4단계  (0) 2013.02.16
[Node.js] 생태계에 대한 생각들  (0) 2012.12.23
[Jade] Jade 사용하기  (0) 2012.12.15
[EJS] 사용하기  (0) 2012.12.15
posted by 윤영식