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

Publication

Category

Recent Post

2013. 2. 20. 16:27 Languages/JavaScript

자바스크립트 개발자가 되고 싶다면 이렇게 배우자. 


1) 이럴때 자바스크립트를 배우자

  - 모던 웹 애플리케이션을 만들고자 할때

  - Backbone.js, Node.js, MongoDB와 같은 프레임워크나 자바스크립트 인터프리터를 탑재한 곳에서 개발 할때


2) 이렇게 배우진 말자

  - 온라인에서 튜토리얼이나 동영상 보고 배우지 말자

  - 초보자에게 더글라스 클락포드의 "JavaScript: The Good Parts" 책은 적합하지 않다 


3) 1~ 3주간 이렇게 배우자 

  - 공부할 책들

    + Professional JavaScript for Web Developers

    + JavaScript: The Definition Guid 6th (번역서 : 자바스크립트 완벽 가이드)

    + 코드아카데미 강좌 이용

  - 코드아카데미 Web Fundamentals 공부

  - Professional JavaScript 책 1장에서 3장까지 공부

  - 코드아카데미 JavaScript Fundamentals 공부

  - Professional JavaScript 책 4장에서 5장까지 쭉 공부

  - Definition Guide는 6장까지 쭉 공부 (번역본 읽어보니 주옥같은 내용이다. 강추)

  - Professional JavaScript 책 18장까지 공부 (원문에 챕터를 너무 분류했다)

  - Definition Guide를 다시 12장까지 공부 (서버사이드 자바스크립트 마스터)


4) 4~5주간 이렇게 배우자 

  - 코드아카데미 jQuery 배우기

  - Professional JavaScript 책 18장부터 끝까지 공부

  - Definition Guide 13장부터 끝까지 공부 (클라이언트 사이드 자바스크립트 마스터)

  - 이후엔 애플리케이션을 만들어 본다 


5) 6주차

  - Node.js를 이용하여 서버 코딩을 한다

  - Backboen.js를 이용하여 클라이언트 코딩을 한다 


6) 이후 좋은 참조 사이트들 공부하기 

  - 자바스크립트 디자인 패턴

  - 자바스크립트 Garden (번역)



<참조>

  - 원문 : http://javascriptissexy.com/how-to-learn-javascript-properly/

posted by 윤영식
2013. 2. 16. 16:42 MongoDB/Prototyping

MongoDB 를 접속하기 위한 다양한 방법에 대해 알아보자 



1. mongodb 

  - REST API 개발하기 : 와인 저장고 요약 블로깅

  - MongoDB Native Driver for Node.js 문서

  - 당연히 mongojs 를 사용하는 것보다 복잡하다



2. mongojs

  - mongodb native를 wrapping한 모듈 

  - 설치 : npm install mongojs  

  - mongoDB에서 컬렉션 만들기 

[~/mongodb:nulpulum]./mongo

MongoDB shell version: 2.2.3

connecting to: test

Welcome to the MongoDB shell.

For interactive help, type "help".

For more comprehensive documentation, see

http://docs.mongodb.org/

Questions? Try the support group

http://groups.google.com/group/mongodb-user

> show dbs

local (empty)

> use dowonDB

switched to db dowonDB

> db

dowonDB

> db.people.save({_id:1, age:11, name: 'dowon', sex: true});

> db.people.save({_id:2, age:22, name: 'youngsik', sex: true});

> db.people.save({_id:3, age:33, name: 'taeyoung', sex: false});

> show collections

people

system.indexes


  - mongojs 코딩

  - Mongo Shell 에서 확인

> db.people.find();

{ "_id" : 1, "age" : 11, "name" : "dowon", "sex" : true }

{ "_id" : 2, "age" : 22, "name" : "youngsik", "sex" : true }

{ "_id" : 3, "age" : 33, "name" : "taeyoung", "sex" : false }

{ "_id" : 4, "age" : 27, "name" : "jaein", "sex" : false }



3. mongoose

  - 가장 많이 사용한다. MongoDB접속 ODM(Object Document Mapping) MVC framework

  - 설치하기 : npm install mongoose

  - mongolian 은 mongoose의 light weight 버전이다 

  - Backbone.js 프레임워크와 유사 : schema = controller 개념으로 사용, model = collections

    하기와 같이 schema에서 할 수 있는 일들은 일반 프레임워크의 컨트롤러 즉, 비즈니스 펑션을 제공한다 (참조)

Validators (async and sync)

Defaults

Getters

Setters

Indexes

Middleware

Methods definition

Statics definition

Plugins

pseudo-JOINs

  

  - Schema를 만들 때 사용하는 타입

String

Number

Date

Buffer

Boolean

Mixed

ObjectId

Array

  

  Functional Programming에서 함수를 인자로 넘기고 동일한 로직을 수행한다면, 인자인 함수를 바꿔가면서 동일한 로직을 DRY 하여 사용할 수 있다. 여기서 인자로 넘기는 함수를 Schema라고 생각해 볼 수 있다

  

  - mongoose 코딩

  - 결과 : save, find가 비동기로 이루어지기 때문에 이미 전에 save한 (age: 33 도큐먼트) 데이터만 나온다 

[nulpulum:~/development/mongoose]node mongoose.js 

connection successful...

{ age: 33,

  name: 'dowon',

  sex: true,

  _id: 511f3cb4c6ae3fef03000001,

  __v: 0 }



4. mongolian

  - Node.js 전용 드라이브

  - 향후 다른 layer와 연결하여 개발하려면 mongoose 또는 mongolian/skin중 하나를 선택하여 사용한다 

    (개인적으로 mongoskin framework이 편리하다)



5. mongoskin

  - 설치하기 

[nulpulum:~/development/nodejs/node_basic]npm install mongoskin

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

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

npm http GET https://registry.npmjs.org/mongoskin/-/mongoskin-0.5.0.tgz

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

npm http GET https://registry.npmjs.org/bson/0.1.8


> bson@0.1.8 install /Users/nulpulum/development/nodejs/node_basic/node_modules/mongoskin/node_modules/mongodb/node_modules/bson

> (node-gyp rebuild 2> builderror.log) || (exit 0)


xcode-select: Error: No Xcode is selected. Use xcode-select -switch <path-to-xcode>, or see the xcode-select manpage (man xcode-select) for further information.


mongoskin@0.5.0 node_modules/mongoskin

└── mongodb@1.2.13 (bson@0.1.8) 


  - 사용하기 : express 코딩

var mongoskin = require('mongoskin');

var db3 = mongoskin.db('localhost:27017/dowonDB?auto_reconnect');


app.get('/person3/list', function(req, res) {

    console.log('---start 04----');

    db3.collection('people').findOne({name: 'young'}, function (err, users) {

        // do something

        if(err || !users) throw err;


        res.json(users);

    });

});


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

// 결과 

[nulpulum:~/development/nodejs/node_basic]curl -i -X GET http://localhost:3000/person3/list

HTTP/1.1 200 OK

X-Powered-By: Express

Content-Type: application/json; charset=utf-8

Content-Length: 90

Date: Sat, 23 Feb 2013 05:54:17 GMT

Connection: keep-alive


{

  "age": "31",

  "name": "young",

  "sex": "true",

  "_id": "51282bb231ca135412000001"


  - mongoskin API 



<참조> 

  - Node.js Language Center in MongoDB

  - https://github.com/gett/mongojs

  - MongoJS 사용하기

  - Mongoose API 사용하기

  - Mongoose Homepage

  - Mongoose API 익히자

posted by 윤영식
2013. 2. 16. 14:56 Testing, TDD/Test First

JavaScript 의 Unit Test를 위하여 여러 프레임워크가 나왔고, 이중 자유도가 높은 Mocha를 사용하려 한다. Assert에 대해 변경을 하면 BDD, TDD를 할 수 있고, JavaScript Funcational 프로그래밍 테스트에 잘 어울리는 BDD를 기본으로 사용한다



1. Test Framework의 종류 

  - Mocha의 장점이 가장 많다 (5page)



2. Mocha 

  - mocha 명령을 수행하는 위치 하위로 test디렉토리에 있는 스크립트를 자동 수행한다 

  - Assertion의 종류를 선택할 수 있다

    + should.js : describe, it 의 BDD 스타일

    + chai : expect(), assert() 스타일

    + expect.js : expect() 스타일 

  - should.js 는 Object prototype에 assert 모듈을 확장하였다 

  - test/mocha.opts 옵션 파일을 놓으면 자동 테스트시에 해당 옵션을 자동 적용한다

--require should
--reporter dot
--ui bdd
--globals okGlobalA,okGlobalB
--globals okGlobalC
--globals callback*

  --timeout 200


  - Mocha의 BDD 스타일 기본형식 

describe('BDD style', function() {

  before(function() {

    // excuted before test suite

  });

 

  after(function() {

    // excuted after test suite

  });

 

  beforeEach(function() {

    // excuted before every test

  });

 

  afterEach(function() {

    // excuted after every test

  });

   

  describe('#example', function() {

    it('this is a test.', function() {

      // write test logic

    });

  });

});




3. 사용법

  - test 폴더 밑에 mocha.opts 파일 작성

    + coffee-script 지원

    + requrie('should') 할 필요 없이 should.js 모듈 첨부

--compilers coffee:coffee-script

--require should


  - 간단한 테스트 프로그램 작성 

    + should.js API 익히기  : Object prototype을 확장하였으므로 Object.should 사용한다 (직관적인 표현이 좋군)

describe('Array', function() {

describe('#indexOf()', function() {

it('should return -1', function() {

[1,2,3].indexOf(5).should.equal(-1);

})

})

})


  -test 폴더와 같은 dept 위치에서 mocha 수행

[nulpulum:~/development/mongojs] mocha


  ․


  1 test complete (1 ms)



<참조>

  - Mocha 사용법 - Outsider

  - mocha.opts

  - 공식홈페이지 http://visionmedia.github.com/mocha/

  - Test Framework Pros and Cons 비교

posted by 윤영식
2013. 2. 16. 11:21 NodeJS/Concept

웹 기술에 대한 발전방향을 고찰해 보자.


1) Physical Level

  - file base - static web (web server : content management, http 통신) - web browser (mime type)

    + Content Delivery Service

  - GET, POST 만 주로 사용



2) Logical Level

  - framework operation (MVC라는 server side기술에서 출발함)

  - controller : request/response, model : data, view : ui  

  - DRY Service: Don't Repeat Yourself 를 위한 좋은 framework으로 요즘 spring 을 기업에서 많이 사용함 

  - Routing 통한 RESTful Web Services : Data Service -> Cloud Service 로 발전 (CRUD 서비스를 GET/POST/PUT/DELETE)

  - RIA 기술의 태동 : 

  - MVC 초기 document base 에서 stream base 로 이동한다. 이에 따라 DB도 code first 로 이동하면서 어플리케이션과 merge를 쉽게 하는 방향으로 이동한다 

  - Data Service로 가면서 View가 없어지면서(None UI) SPA(MS의 서버사이드 기술임)을 스티브 샌더슨이 말하고 있다

  - 즉,  RIA (activex, flash, etc) -> SPA 로 변해감 (기술이 JavaScript로 통일되어 감)

  - application level 이다 



3) SNS Level

  - SNS 기술 : community level, Service Level 이다 

  - 2)의 application level 과 service level 로 구분된다 

  - Client-WebApp, Server-Node.js, NoSQL-MongoDB 기술들의 등장 

  - Client Side에서 SPA (Single Page Application)등장 : Backbone(Underscore), Angular (DI 존재), Ember (DI 없음)

   + 2)레벨의 MVC는 의미가 희석됨

   + Backbone의 $el 는 3세대 jQuery 라고 보면됨 

   + Functional programming이 가능 

   + Backbone -> AngularJS로 이동하면 된다 

  - Client + Server + Store 를 합치는 기술 = Meteor 또는 Derby 

  - MV* = Functional 이라는 개념으로 이동한다. 이것은 뷰가 모델이 되고, 컨트롤러가 없어지고, 나뉘었다 합쳐졌다하면서 데이터만 남는다. 즉, 과거 MVC 처럼 역할이 나뉘지 않는다

   


4) Contextual Level

  - 융합 서비스

  - Trend (500만) -> Culture (1000만) 즉, SNS를 통하여 트랜드나 문화로 가는 서비스 레벨

  - 데이터에 대한 MapReduce만 남는다 

    + Map = Key + Value 예) JSON

    + Reduce Function = Business Intelligence 솔루션으로 가는 것이다


결론, 기술 변천을 느끼고 만들어 가려면 Coding 하자.... ^^


<참조>

  - KOSTA : 이복영 강사, MongoDB/Node.js 강의 4주차 

posted by 윤영식
2013. 2. 7. 21:28 Testing, TDD/Test First

Mocha는 Node.js를 위한 테스트 프레임워크이다. test 스크립트가 변경되었을 때 계속 감시하면서 다시 mocha 테스트를 해주도록 Continuously Testing이 가능하도록 Nodemon을 적용해 본다


1) Mocha 와  Nodemon 설치하기 

  - mocha 설치

$ npm install -g mocha

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

... 중략 ...

npm http 200 https://registry.npmjs.org/mkdirp/-/mkdirp-0.3.0.tgz

C:\Documents and Settings\UserXP\Application Data\npm\mocha -> C:\Documents and Settings\UserXP\Application Data\npm\node_modules\mocha\bin\mocha

C:\Documents and Settings\UserXP\Application Data\npm\_mocha -> C:\Documents and Settings\UserXP\Application Data\npm\node_modules\mocha\bin\_mocha

mocha@1.8.1 C:\Documents and Settings\UserXP\Application Data\npm\node_modules\mocha

├── growl@1.7.0

├── commander@0.6.1

├── diff@1.0.2

├── debug@0.7.2

├── ms@0.3.0

├── mkdirp@0.3.3

└── jade@0.26.3 (mkdirp@0.3.0)


  - nodemon 설치하기 

   + node.js를 기반으로 개발할  때 사용한다 

   + hang이 걸리면 자동으로 re-running 시켜준다

   + 여러 디렉토리를 감시할 수 있다 (--watch 옵션적용하면 내용 변경시 node auto restart)

$ npm install -g nodemon

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

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

npm http GET https://registry.npmjs.org/nodemon/-/nodemon-0.7.2.tgz

npm http 200 https://registry.npmjs.org/nodemon/-/nodemon-0.7.2.tgz

C:\Documents and Settings\UserXP\Application Data\npm\nodemon -> C:\Documents and Settings\UserXP\Application Data\npm\node_modules\nodemon\nodemon.js

nodemon@0.7.2 C:\Documents and Settings\UserXP\Application Data\npm\node_modules\nodemon



2) Mocha 테스트 코드 만들기

  - mocha가 수행되는 위치의 test 디렉토리밑의 .js 파일을 자동 테스팅한다

  - BDD 테스트 코드 

  - mocha 수행 

// test 디렉토리가 존재 

$ ls

test


// mocha 명령을 수행하여 test 디렉토리의 mocha_sample.js 를 자동 수행하여 준다 

$ mocha


  .


  1 test complete (3 ms)



3) nodemon으로 mocha 수행하기 

  - nodemon을 mocha 위치를 지정하여 준다 

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

// 정상 테스트 코드

$ nodemon "C:\Documents and Settings\UserXP\Application Data\npm\node_modules\mocha\bin\mocha"

7 Feb 21:24:52 - [nodemon] v0.7.2

7 Feb 21:24:52 - [nodemon] watching: d:\Development\mocha

7 Feb 21:24:52 - [nodemon] starting `node C:\Documents and Settings\UserXP\Application Data\npm\node_modules\mocha\bin\mocha`


  .


  1 test complete (3 ms)


7 Feb 21:24:52 - [nodemon] clean exit - waiting for changes before restart


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

// 코드를 수정하며 에러 발생

// indexOf(0) 을 indexOf(1) 변경

7 Feb 21:26:00 - [nodemon] starting `node C:\Documents and Settings\UserXP\Application Data\npm\node_modules\mocha\bin\mocha`


  .


  × 1 of 1 test failed:


  1) Array #indexOf() should return -1 when the value is not present:


  AssertionError: -1 == 0

      at Context.<anonymous> (d:\Development\mocha\test\mocha_sample.js:6:14)

      at Test.Runnable.run (C:\Documents and Settings\UserXP\Application Data\npm\node_modules\mocha\lib\runnable.js:213:32)

      at Runner.runTest (C:\Documents and Settings\UserXP\Application Data\npm\node_modules\mocha\lib\runner.js:343:10)

      at Runner.runTests.next (C:\Documents and Settings\UserXP\Application Data\npm\node_modules\mocha\lib\runner.js:389:12)

      at next (C:\Documents and Settings\UserXP\Application Data\npm\node_modules\mocha\lib\runner.js:269:14)

      at Runner.hooks (C:\Documents and Settings\UserXP\Application Data\npm\node_modules\mocha\lib\runner.js:278:7)

      at next (C:\Documents and Settings\UserXP\Application Data\npm\node_modules\mocha\lib\runner.js:226:23)

      at Runner.hook (C:\Documents and Settings\UserXP\Application Data\npm\node_modules\mocha\lib\runner.js:246:5)

      at process.startup.processNextTick.process._tickCallback (node.js:244:9)


7 Feb 21:26:01 - [nodemon] app crashed - waiting for file changes before starting...


  - 위의 명령을 넣고 C:\Documents and Settings\UserXP\Application Data\npm\cmocha.cmd 파일을 만든다

  - cmocha.cmd를 수행하면 위와 똑같이 수행위치 하단에 test 디렉토리가 있다면 continuous mocha를 수행한다 



<참조>

  - 원문 : Automating Testing with Mocha and WebStorm

  - Mocha 소개

posted by 윤영식