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

Publication

Category

Recent Post

2013. 1. 25. 09:20 Git, GitHub

Git을 배우려면 다음과 같이 하자. 


1. Git 레퍼런스와 강좌 사이트 

  - Pro Git 한글 번역본 완독

  - http://gitimmersion.com : 사이트 튜토리얼 수행 

  - http://gitready.com : 초심자, 중급, 고급 명령 수행

  - http://gitref.org : Git Reference 에서 바로 Cheat

  - Git Cheatsheet : UI에서 명령흐름을 직관적으로 보여줌


2. 도전과제 

  - PPT의 내용을 직접 수행해 보자  


posted by 윤영식
2013. 1. 25. 09:05 Git, GitHub/Git Lec02

Git commit 할 때 가이드 라인을 잘 지켜서 원격 저장소에 소스가 꼬이지 않도록 하고, 커밋된 내역을 잘 이해할 수 있도록 메세지 작성 정책에 대해 알아보자


  - 공백 문자를 깨끗이 제거 한다 : 확인)  git diff --check (공백 문자 오류확인가능, 잘 못 사용한 공백은 X 문자로 바꿈)

  - 최대한 수정사하을 하나의 주제로 요약한다

    + 여러 가지 이슈에 대한 수정사항을 하나의 커밋에 담지 말아라

    + 적절한 메세지를 작성한다 : 반드시 좋으 커밋 메세지를 담는다


  - 같은 파일의 다른부분을 수정하는 경우에는 git add -patch 명령을 이용한다 

    + 한 부분씩 나누어 Stage 영역에 저장해야 한다 


  - 메세지 작성

    + 첫줄엔 50자내로 간략히 요약

    + 두번째줄 비우고 세번째줄에 자세히 설명글 :개발동기, 구현 상황, 제약조건/상황

    + 글은 현재형을 사용한다 

    + 추가 내용은 한줄 띄우고 시작한다 

    + 잘쓰여진 커밋 메세지는 git log --no-merges 명령으로 꼭 살펴본다 

   예)

   

posted by 윤영식
2013. 1. 25. 08:44 Git, GitHub/Git Lec02

Git은 분산 버전관리 시스템이다. 서로 각자의 저장소를 가지고서 어떻게 충돌없이 잘 사용할 수 있을지 알아보자. (5장)


1) 중앙집중식 Workflow

  - 예전의 Subversion에 익숙한 사용자들의 방식

  - 예로 2명이 작업, 한명이 서버로 update코드 push하면 다른한명이 서버에서 update코드를 pull하여 merge 수행

  - 모든 사용자에게 서버에 push 권한을 부여해야 함

  - 그러나 중앙 서버 저장소로 a코드가 다른이에 의해 push 되었고, 다른사람이 a코드를 수정하여 push해도 Git은 이것을 방지해 준다. 즉, 다시 로컬로 fetch 또는 pull 하지 않으면 중앙 서버로 push 할 수 없게 막아준다




2) 통합관리(Integration-Manager) Workflow

  - 여러 리모트 저장소를 두고 한개는 R/W 가능, 다른 한개는 R만 가능하게 설정가능 하다

  - 이것은 GitHub의 운영방식이다. Pull Request 수행하면 통합관리자가 이것을 보고 기여자의 저장소에서 원본 저장소로 pull하여 merge 하게 된다

 



3) 독재자 보조관(Dictator and Lieutenants) Workflow

  - 2)번 형태의 확장판

  - Linux Kernel과 같은 큰 프로젝트에서 사용한다 

 


* 다양한 변종의 Workflow가 존재함 


<참조>

  - 성공적인 Git Branch 전략 (한글번역본 - dogfeet)

    + feature : 기능 만들기 

    + develop : 개발진행

    + release : 릴리즈 

    + hotfixes : 긴급 패치 

    + master : 원본 



posted by 윤영식
2013. 1. 24. 21:58 AngularJS/Concept

Twitter Bootstrap과 Node.js를 이용하여 Single Page App을 만들어 보자. 여기서는 Backbone.js를 배제하고 만드는 방법이다. 외국 블로깅 글을 따라서 실행보면서 정리한다. (총 3 part중 part 1)


서버단 코드 만들기


1) GitHub에서 소스 다운로드 및 사전 설정

  - 소스 다운로드 : $ git clone https://github.com/iatek/one-page-app.git

  - node.js 와 npm 이 설치되어 있어야 한다

  - Express 프레이워크 설치 : npm install express

  - ejs 템플릿 엔진 설치 : npm install ejs npm install ejs-locals

$ npm install ejs-locals

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

npm http 304 https://registry.npmjs.org/ejs-locals

ejs-locals@1.0.2 node_modules\ejs-locals


// ejs 설치 안하면 에러 발생함 

UserXP@NUKNALEA /d/Git_repositories/one-page-app (master)

$ node server


module.js:340

    throw err;

          ^

Error: Cannot find module 'ejs'

    at Function.Module._resolveFilename (module.js:338:15)

    at Function.Module._load (module.js:280:25)

    at Module.require (module.js:362:17)

    at require (module.js:378:17)

    at Object.<anonymous> (d:\Git_repositories\one-page-app\node_modules\ejs-locals\index.js:1:73)

    at Module._compile (module.js:449:26)

    at Object.Module._extensions..js (module.js:467:10)

    at Module.load (module.js:356:32)

    at Function.Module._load (module.js:312:12)

    at Module.require (module.js:362:17)


UserXP@NUKNALEA /d/Git_repositories/one-page-app (master)

$ npm install ejs

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

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

ejs@0.8.3 node_modules\ejs


// 정상 수행됨 

UserXP@NUKNALEA /d/Git_repositories/one-page-app (master)

$ node server

Listening on port 4000 in development mode


// 로컬에서 브라우져 호출시 reponsive web으로 반응한다 -width를 줄이면 메뉴자동변경됨- (데모확인)


  


2) Express 환경파일 설정

  - app.js

app.js


// ejs template engine 사용
var express = require('express'),
	engine = require('ejs-locals'),   
	app = express();

// init export
exports.init = function(port) {
    app.locals({
		_layoutFile:'layout.ejs'
	})
	
    app.configure(function(){
    	app.set('views', __dirname + '/views');
    	app.set('view engine', 'ejs');
    	app.use(express.bodyParser());
    	app.use(express.methodOverride());
        // Static pages 서비스 
        app.use(express.static(__dirname + '/static'));
        // Session과 Cookie 관리 
        app.use(express.cookieParser());
        app.use(express.cookieSession({cookie:{path:'/',httpOnly:true,maxAge:null},secret:'skeletor'}));
    	app.use(app.router);
    	//app.enable("jsonp callback");
    });

    app.engine('ejs', engine);	
    app.configure('development', function(){
        app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 
        // app.use(express.logger({ format: ':method :url' }));
    });

    app.configure('production', function(){
	   app.use(express.errorHandler()); 
    });

    app.use(function(err, req, res, next){
	   res.render('500.ejs', { locals: { error: err },status: 500 });	
    });
	
    server = app.listen(port);
    console.log("Listening on port %d in %s mode", server.address().port, app.settings.env);
    return app;
}


3) Routing 만들기 

  - server.js : app이 시작하는 초기 파일이다. app route를 정의한다

server.js


  - "app.get", "app.post", "app.del" 을 사용한다 

  - 4개의 HTTP get routing 호출  

    /(default homepage)

    /login

    /logout

    /admin

var port = process.env.PORT || 4000,
    app = require('./app').init(port),
	dirty = require('dirty');
	
var locals = {
	author:'in1'
	// add other vars here
};

var userDb = dirty('user.db');

app.get('/', function(req,res){
    locals.date = new Date().toLocaleDateString();
	
	var appDb = dirty('app.db'),
		sectionsDb;
	
	appDb.on('load', function() {
		sectionsDb = dirty('sections.db');
		sectionsDb.on('load', function() {
			/*
			sectionsDb.forEach(function(key, val) {
				console.log('Found key: %s, val: %j', key, val);
			});
			*/
			res.render('index.ejs', {locals:locals,sections:sectionsDb,app:appDb.get('app'),page:appDb.get('page')});
		});
	});
});
... 중략 ...
app.post('/contact', function(req,res){
	appDb = dirty('app.db');
	console.log('contact form submit.');
	
	appDb.on('load', function() {
		console.log('Form submitted.');
		res.send('Thank you.');
	});
});

/* The 404 Route (ALWAYS Keep this as the last route) */
app.get('/*', function(req, res){
    res.render('404.ejs', locals);
});


4) Persistence 유지 하기 

  - Node-Dirty를 이용하여 disk log형태로 가벼운 데이터베이스겸으로 사용한다

  - 5개의 database 파일안에 관련 표현할 내역이 .db파일에 들어있음 (백만 record 미만 사용하는 앱에 적당)

    app.db : 애플리케이션 래벨 설정

    sections.db : 섹션 설정과 내용 저장

    user.db : 사용자 credential 과 admin 권한

    snippet.db : 미리 생성할 섹션 내용을 위한 코드 조각 저장

    post.db : 연락처와 이메일 폼 결과 저장 

  - server.js에서 require('dirty')


> 다음은 UI Part to be continued...


<참조>

  - Single Page App with Twitter Bootstrap and Node.js : 데모사이트

  - One page app GitHub 소스

  - SPA를 위한 storage : node-dirty

  - Node.js 기초 강의 동영상

  - Node의 MVC Framework : Express.js

  - Bootstrap 확장판

posted by 윤영식
2013. 1. 24. 21:57 NodeJS

Node.js 기반하에 Front-end 개발을 할 경우 텍스트 기반의 툴들을 알아보자.

  - Node.js로 개발할 때 commmand-line 유틸리티가 상당히 많고 이는 front-end 개발자에게 도움을 준다 

  - 다섯가지의 Node CLI 유틸리티를 알아보자 

  - Node와 npm이 설치되어 있음을 전제로 한다 



1) UglifyJS

  - JavaScript를 압축하고 사이즈를 최소화해준다 (네트워크 전송량을 작게해서 성능향상을 기대할 수 있다) 

  - UglifyJS의 기능을 바로 웹상에서 사용하기   

- 설치하기 

D:\Development>npm install -g uglify-js

npm http GET https://registry.npmjs.org/uglify-js


- 명령어

uglifyjs -b -o <output file> <input file>


-b 옵션 : beautifies

D:\Development>uglifyjs -b -o d:\development\if_uglify.js d:\development\if.js

D:\Development>uglifyjs -o d:\development\if_uglify.js d:\development\if.js

// coffee에서 컴파일된 javascript 소스 
// Generated by CoffeeScript 1.4.0
(function() {
  var x;

  x = 4;

  if ((0 <= x && x <= 10)) {
    console.log("true");
  }

}).call(this);

// -b 옵션을 주었을 경우 
(function() {
    var x;
    x = 4;
    if (0 <= x && x <= 10) {
        console.log("true");
    }
}).call(this);

// -b 옵션을 주지 않았을 경우 
(function(){var x;x=4;if(0<=x&&x<=10){console.log("true")}}).call(this);



2) Grunt

  - JavaScript 프로젝트를 위한 task-based command line 빌드 툴

  - 미리 정의된 템플릿을 만들어 준다 : 테스트(QUnit & PhantomJS), Lint파일(JSHint), 최소화파일(UglifyJS), Static WebServer

  - 템플릿들은 Node Server에서 구동할 수 있다. (jQuery 템플릿도 가능)

  - 시작하기 가이드

  - Grunt 간단 소개

  - 좀 더 자세한 튜토리얼

- 설치하기 : 상당히 많은 모듈을 함께 설치한다

D:\Development>npm install -g grunt

... 중략 ...

grunt

├── dateformat@1.0.2-1.2.3

├── colors@0.6.0-1

├── semver@1.0.14

├── async@0.1.22

├── hooker@0.2.3

├── underscore@1.2.4

├── underscore.string@2.1.1

├── uglify-js@1.3.4

├── nopt@1.0.10 (abbrev@1.0.4)

├── gzip-js@0.3.1 (crc32@0.2.2, deflate-js@0.2.2)

├── temporary@0.0.5 (package@1.0.1)

├── glob-whatev@0.1.8 (minimatch@0.2.9)

├── connect@2.4.6 (fresh@0.1.0, cookie@0.0.4, pause@0.0.1, bytes@0.1.0, crc@0.2.0, debug@0.7.0, formidable@1.0.11, qs@0.5.1, send@0.0.4)

├── prompt@0.1.12 (pkginfo@0.3.0, winston@0.5.11)

├── jshint@0.9.1 (minimatch@0.0.5, cli@0.4.3)

└── nodeunit@0.7.4 (tap@0.4.0)


- jquery 템플릿 만들어보기

// 신규 디렉토리를 만듦

D:\Development\grunt>mkdir jquery

// 디렉토리 이동

D:\Development\grunt>cd jquery

// 명령 수행 

D:\Development\grunt\jquery>grunt init:jquery

Running "init:jquery" (init) task

This task will create one or more files in the current directory, based on the environment and the answers to a few questions. Note that answering "?" to any question will show question-specific help and answering "none" to most question


will leave its value blank.


"jquery" template notes:

Project name should not contain "jquery" or "js" and should be a unique ID not already in use at plugins.jquery.com. Project title should be a human-readable title, and doesn't need to contain the word "jQuery", although it may. For

example, a plugin titled "Awesome jQuery Plugin" might have the name "awesome-plugin". For more information please see the documentation at https://github.com/jquery/plugins.jquery.com/blob/master/docs/manifest.md


// 질문에 값을 입력한다 

Please answer the following:

[?] Project name jQueryTest

[?] Project title (jQuerytest) DoWonQuery

[?] Description (The best jQuery plugin ever.)

[?] Version (0.1.0)

[?] Project git repository (git://github.com/UserXP/jQueryTest.git)

[?] Project homepage (https://github.com/UserXP/jQueryTest)

[?] Project issues tracker (https://github.com/UserXP/jQueryTest/issues)

[?] Licenses (MIT)

[?] Author name (none)

[?] Author email (none)

[?] Author url (none)

[?] Required jQuery version (*)

[?] Do you need to make any changes to the above before continuing? (y/N)


Writing CONTRIBUTING.md...OK

Writing grunt.js...OK

Writing libs/jquery/jquery.js...OK

Writing libs/jquery-loader.js...OK

Writing libs/qunit/qunit.css...OK

Writing libs/qunit/qunit.js...OK

Writing README.md...OK

Writing src/jQueryTest.js...OK

Writing test/jQueryTest.html...OK

Writing test/jQueryTest_test.js...OK

Writing LICENSE-MIT...OK


Initialized from template "jquery".

Done, without errors.

// 필요한 라이브러리와 grunt.js 환경파일이 자동 생성된다 

D:\Development\grunt\jquery>dir

2013-01-25  오후 05:32    <DIR>          .

2013-01-25  오후 05:32    <DIR>          ..

2013-01-25  오후 05:32             2,091 CONTRIBUTING.md

2013-01-25  오후 05:32             1,547 grunt.js

2013-01-25  오후 05:32               551 jQueryTest.jquery.json

2013-01-25  오후 05:32    <DIR>          libs

2013-01-25  오후 05:32             1,066 LICENSE-MIT

2013-01-25  오후 05:32               199 package.json

2013-01-25  오후 05:32               604 README.md

2013-01-25  오후 05:32    <DIR>          src

2013-01-25  오후 05:32    <DIR>          test

               6개 파일               6,058 바이트

               5개 디렉터리  37,356,339,200 바이트 남음



3) GruntIcon

  - css icon 만들기

  - PhantomJS가 필요하다 (phantomjs.exe 파일을 프로젝트 폴더에 놓는다)

  - grunt.js 파일에 GruntIcon 로드 설정을 한다

- 설치

D:\Development\grunt\jquery>npm install grunt-grunticon

npm http GET https://registry.npmjs.org/grunt-grunticon

... 중략 ...

grunt-grunticon@0.1.4 node_modules\grunt-grunticon

└── grunt@0.3.17 (dateformat@1.0.2-1.2.3, colors@0.6.0-1, semver@1.0.14, asyn

c@0.1.22, hooker@0.2.3, underscore@1.2.4, underscore.string@2.1.1, uglify-js@1.3

.4, nopt@1.0.10, gzip-js@0.3.1, temporary@0.0.5, glob-whatev@0.1.8, connect@2.4.

6, jshint@0.9.1, prompt@0.1.12, nodeunit@0.7.4)


- grunt.js 파일 설정 넣기 

/*global module:false*/

module.exports = function(grunt) {


  // Project configuration.

  grunt.initConfig({

    pkg: '<json:jQueryTest.jquery.json>',

    meta: {

      banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +

        '<%= grunt.template.today("yyyy-mm-dd") %>\n' +

        '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +

        '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +

        ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'

    },

    concat: {

      dist: {

        src: ['<banner:meta.banner>', '<file_strip_banner:src/<%= pkg.name %>.js>'],

        dest: 'dist/<%= pkg.name %>.js'

      }

    },

    min: {

      dist: {

        src: ['<banner:meta.banner>', '<config:concat.dist.dest>'],

        dest: 'dist/<%= pkg.name %>.min.js'

      }

    },

    qunit: {

      files: ['test/**/*.html']

    },

    lint: {

      files: ['grunt.js', 'src/**/*.js', 'test/**/*.js']

    },

    watch: {

      files: '<config:lint.files>',

      tasks: 'lint qunit'

    },

    jshint: {

      options: {

        curly: true,

        eqeqeq: true,

        immed: true,

        latedef: true,

        newcap: true,

        noarg: true,

        sub: true,

        undef: true,

        boss: true,

        eqnull: true,

        browser: true

      },

      globals: {

        jQuery: true

      }

    },

    uglify: {},

    grunticon: {

      src: "src/icons-source/",

      dest: "src/icons-output/"

    }

  });


  // Default task.

  grunt.registerTask('default', 'lint qunit concat min');

  grunt.loadNpmTasks('grunt-grunticon');

};


- grunticon 생성 (윈도우: grunt.cmd, 리눅스 : grunt )
D:\Development\grunt\jquery>grunt.cmd grunticon
Running "grunticon" task
Look, it's a grunticon!

grunticon now minifying the stylesheet loader source.
grunticon loader file created.
grunticon now spawning phantomjs...
Done, without errors.

// grunt.js에 환경설정한 icon-output이 생성된다 



4) JSHint

  - JavaScript의 코드 품질 측정 툴 

  - 잠재적인 위험 요소를 찾아준다 : 웹기반 측정도 가능

- 설치

D:\Development\grunt\jquery>npm install -g jshint

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

npm http 304 https://registry.npmjs.org/jshint

npm http GET https://registry.npmjs.org/cli/0.4.3

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

npm http 304 https://registry.npmjs.org/cli/0.4.3

npm http 304 https://registry.npmjs.org/minimatch

npm http GET https://registry.npmjs.org/lru-cache

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

npm http 304 https://registry.npmjs.org/lru-cache

npm http 304 https://registry.npmjs.org/glob

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

npm http GET https://registry.npmjs.org/graceful-fs

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

npm http 304 https://registry.npmjs.org/graceful-fs

npm http 304 https://registry.npmjs.org/inherits

npm http 304 https://registry.npmjs.org/minimatch

npm http GET https://registry.npmjs.org/lru-cache

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

npm http 304 https://registry.npmjs.org/sigmund

npm http 304 https://registry.npmjs.org/lru-cache

C:\Documents and Settings\UserXP\Application Data\npm\jshint -> C:\Documents and

 Settings\UserXP\Application Data\npm\node_modules\jshint\bin\hint

jshint@0.9.1 C:\Documents and Settings\UserXP\Application Data\npm\node_modules\

jshint

├── minimatch@0.0.5 (lru-cache@1.0.6)

└── cli@0.4.3 (glob@3.1.17)

 

- 수행 : jshint <file to check>

D:\Development>jshint loop.js

loop.js: line 15, col 2, Mixed spaces and tabs.


1 error



5) Node-static

  - 로컬 테스트시에 캐쉬/헤더 별도 셋팅가능

  - 로컬 웹서버로서 아무 디렉토리에서나 시작하면 ROOT 디렉토리가 된다

- 설치

D:\Development>npm install -g node-static

npm http GET https://registry.npmjs.org/node-static

npm http 200 https://registry.npmjs.org/node-static

npm http GET https://registry.npmjs.org/node-static/-/node-static-0.6.7.tgz

npm http 200 https://registry.npmjs.org/node-static/-/node-static-0.6.7.tgz

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

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

npm http 304 https://registry.npmjs.org/colors

npm http 304 https://registry.npmjs.org/optimist

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

npm http 304 https://registry.npmjs.org/wordwrap

C:\Documents and Settings\UserXP\Application Data\npm\static -> C:\Documents and

 Settings\UserXP\Application Data\npm\node_modules\node-static\bin\cli.js

node-static@0.6.7 C:\Documents and Settings\UserXP\Application Data\npm\node_mod

ules\node-static

├── colors@0.6.0-1

└── optimist@0.3.5 (wordwrap@0.0.2)


- 수행 : 아무 디렉토리나 가서 수행 -> 브라우져에서 호출한다 

D:\Development>static

serving "." at http://127.0.0.1:8080


- 또는 8080이 사용중이라면 옵션을 준다 

static -p <port>  <directory> 


* CLI를 이용하여 브라우져안에서 클라이언트단 유닛 테스트 도구 : bunyip


<참조> 

'NodeJS' 카테고리의 다른 글

[Node.js] 라이언 일병 이야기 이해하기  (0) 2012.12.08
[Node.js] 역사와 기초  (0) 2012.12.08
[Node.js] 시작하기  (1) 2012.10.30
posted by 윤영식