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

Publication

Category

Recent Post

2013. 8. 14. 14:32 NodeJS/Modules

Node.js 프로젝트에서 사용된 자신의 모듈을 공유하고 싶다면 NPM Regsitry를 이용하면 된다. Publis Registry에 등록하고 사용하는 방법에 대해 알아보자 



1. NPM Registry

  - NPM Registry는 누구나 Node.js에서 사용할 수 있는 모듈을 일정한 양식만 갖춘다면 등록할 수 있고,  

    npm 명령을 통하여 Module Registry 에서 필요한 모듈을 설치할 수 있다

  - 홈페이지 : https://npmjs.org/

  - 홈페이지에서 계정을 미리 생성해 놓자 : 자신이 등록한 모듈 목록을 볼 수 있다

    




2. 배포전 준비하기 

  - .npmignore 파일 : npm 저장소에 배포하지 않을 것들에 대해 열거한다. 해당 파일이 없을 경우 .gitignore를 사용한다 

// .gitignore 내역 

.DS_Store

.git*

node_modules/

  - 모듈이 이미 GitHub에 등록되고 npm init을 통하여 package.json 파일 내역이 정확히 장성되었음을 가정한다 (참조)

// package.json 내역 

// 주의)

// npm init으로 해당 파일 생성시 engines 내역은 포함되지 않는 관계로 사용하는 Node.js 버전을 명시하여 준다 

// name : 값은 대문자와 띄워쓰기 없이 소문자로 이어서 작성한다 

// version : semantic versioning을 사용한다 major.minor.patch

// main : 프로그램 진입점

// test : 테스트 프로그램 수행 스크립트 명령 (npm test)

{

  "name": "mobiconstatistics",

  "version": "0.0.1",

  "description": "include statistics function such as the moving average",

  "main": "./lib/mobiconStatistics.js",

  "engines": { "node": ">= 0.10.0" }, 

  "dependencies": {

    "underscore": "~1.5.1"

  },

  "devDependencies": { 

    "mocha": "latest",

    "should": "~1.2.2"

  },

  "scripts": {

    "test": "mocha test/*.js"

  },

  "repository": {

    "type": "git",

    "url": "https://github.com/ysyun/mobiconStatistics.git"

  },

  "keywords": [

    "mobicon",

    "statistics",

    "movingAverage"

  ],

  "author": "yun youngsik",

  "license": "MIT",

  "bugs": {

    "url": "https://github.com/ysyun/mobiconStatistics/issues"

  }

}




3. 배포하기 

  - https://www.npmjs.org/ 사이트에 가입을 한다.

  - 모듈 디렉토리로 이동하고 사용자를 추가합니다 : npm adduser 

  - 가입했던 username과 password등을 입력하면 된다.

Users/development/node-modules/mobiconStatistics> npm adduser

Username: (ysyun)

Password: 

Email: 

  - 모듈 배포전 npm install이 잘 되는지 테스트 합니다 

    test 폴더를 하나 만들어서 기존에 만든 모듈을 install 해봅니다. test 폴더에 node_modules/mobiconstatistics 모듈을 설치되면 성공!

/Users/development/node-modules/mobiconStatistics> mkdir ../mobiconStatistics-installTest

/Users/development/node-modules/mobiconStatistics> cd ../mobiconStatistics-installTest

/Users/development/node-modules/mobiconStatistics-installTest> npm install ../mobiconStatistics

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

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

mobiconstatistics@0.0.1 node_modules/mobiconstatistics

└── underscore@1.5.1


/Users//development/node-modules/mobiconStatistics-installTest/node_modules/mobiconstatistics> ls

-rw-r--r--  1   staff  1096  8 13 17:09 LICENSE

drwxr-xr-x  3   staff   102  8 13 17:31 test

drwxr-xr-x  3   staff   102  8 13 17:41 lib

-rw-r--r--  1   staff    49  8 14 11:26 .travis.yml

-rw-r--r--  1   staff   904  8 14 11:34 README.md

-rw-r--r--  1   staff  1881  8 14 14:19 package.json

drwxr-xr-x  3   staff   102  8 14 14:19 node_modules

  - 모듈을 배포합니다 : npm publish

Users//development/node-modules/mobiconStatistics> npm publish                          

npm http PUT https://registry.npmjs.org/mobiconstatistics

npm http 201 https://registry.npmjs.org/mobiconstatistics

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

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

npm http PUT https://registry.npmjs.org/mobiconstatistics/-/mobiconstatistics-0.0.1.tgz/-rev/1-b8e34dc09489f8c4c9ece305d250264a

npm http 201 https://registry.npmjs.org/mobiconstatistics/-/mobiconstatistics-0.0.1.tgz/-rev/1-b8e34dc09489f8c4c9ece305d250264a

npm http PUT https://registry.npmjs.org/mobiconstatistics/0.0.1/-tag/latest

npm http 201 https://registry.npmjs.org/mobiconstatistics/0.0.1/-tag/latest

+ mobiconstatistics@0.0.1

  - 모듈이 잘 배포되었는지 확인합니다 : http://npmjs.org/package/<모듈명>

    예) https://npmjs.org/package/mobiconstatistics

    




4. 모듈 사용하기 

  - 이제 npm registry로 자신의 모듈이 배포되었으므로 프로젝트에 첨부하여 사용할 수 있게 되었습니다. 

// mobiconstatistics 모듈 추가하기 

/Users/development/smart-solutions/SmartStatistics> npm install mobiconstatistics --save

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

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

mobiconstatistics@0.0.1 node_modules/mobiconstatistics


// 프로젝트의 package.json에 mobiconstatistics 모듈 추가

/Users/development/smart-solutions/SmartStatistics> cat package.json

{

  "name": "smartstatistics",

  "version": "0.0.0",

  "dependencies": {

    "sails": "0.8.9",

    "express": "~3.2.6",

    "ejs": "~0.8.4",

    "underscore": "~1.5.1",

    "mobiconstatistics": "0.0.1"

  },

  - 트위터에서 npm registry에 배포된 모듈중 괜찮은 것들을 정리하여 트윗을 해준다 : @nodenpm

    



<참조>

  - Node.js 소개 in opentutorial

  - npm 이란? 

  - Node Module NPM Registry 등록하기

  - npm developer 가이드

posted by 윤영식
2013. 3. 16. 16:56 NodeJS/Modules

AMD를  사용하지 않으면 엔터프라즈급의 웹앱을 만들 수가 없다. 요즘 Java 에서 Spring Framework이 엔터프라이즈 구현에 핵심이듯이 서로의 의존관계를 관리하고 주입하여 준다. 전통적인 방식은 HTML에서 <script> 태그를 사용하여 모듈들을 순차적으로 코딩한다. 그런 순차적 코딩이 아닌 모듈개념으로 어떻게 전환할 수 있는지 알아보자 



1) 예전 방식의 자바스크립트 로딩방식

  - html 코드

    + add.js : 더하기 연산

    + multi.js : 곱하기 연산

    + app.js : add, multi 연산을 사용하고 결과 출력

<html>

<body>

<script type="text/javascript" src="add.js"></script>

<script type="text/javascript" src="multi.js"></script>

<script type="text/javascript" src="app.js"></script>

</body>

</html>


  - 나머지 코드들

    + 전역변수 cal를 사용하기 위하여 모든 .js에서 undefined을 확인해야 한다

// add.js 

var cal = cal || {};


cal.add = function(x, y) {

return x + y;

}


// multi.js

var cal = cal || {};


cal.multiply = function(x, y) {

return x*y;

}


// app.js 

// 전역변수 cal를 이용하여 호출한다 

console.log('add result is ' + cal.add(4, 5));

console.log('multi result is ' + cal.multiply(4, 5));


  - html 호출 결과 

  



2) AMD 방식으로 로딩하기

  - add.js, multi.js  모듈화를 위하여 define() 펑션을 이용한다

  - app.js 에서 모듈을 사용하기 위하여 require() 펑션을 이용한다

// add.js 

// var cal 과 같은 변수 선언이 없어졌다. 

// 1) Functional Programming의 최대 장점이 변수 설정으로 인한 메모리 할당이 필요없어지게 되었다

// 2) Anonymous Function == Closure Function으로 만들었다  

define(function() {

return function(x, y) {

return x + y;

}

}) 


// multi.js

define(function() {

return function(x, y) {

return x * y;

}

})


// app.js

// 의존관계에 있는 것을 require의 첫번째 인자에 배열로 설정한다 

require(['add', 'multi'], function(add2, multi2) {

console.log('AMD : add result is ' + add2(4, 5));

console.log('AMD : multi result is ' + multi2(4, 5));

});


  - AMD 구현체 require.js를 사용하여 index.html 을 변경한다 

    + data-main 값으로 app.js 를 지정한다

    + src 값으로 require.js 를 지정한다 

<html>

<BODY>

<script data-main="app" src="http://requirejs.org/docs/release/2.1.5/minified/require.js"></script>

</BODY>

</html>


  - 결과 확인

  


** 테스트 소스

AMD.zip



<참조>

  - Require.js 홈페이지

  - Require.js 이용하여 AMD 모듈 작성하기

posted by 윤영식
2013. 3. 16. 12:34 NodeJS/Modules

Node.js에서 모듈을 사용하는 방법과 브라우져에서 SPA(Singe page application) 기반으로 개발을 진행할 때 Javascript 모듈의 의존성 관계 관리를 위한 모듈 사용방법은 차이가 있다. 각각에 대해 간단히 알아보자 


1) Node.js 모듈 

  - CommonJS 패턴을 사용한다 : Synchronous 로딩이다 

  - require('dowon') 방식으로 module을 로딩한다 

  - module.exports 를 통하여 functionality를 노출시킨다. 모듈이라는 컴포넌트를 사용하기 위한 외부 Interface를 지정하는 것이다.


  - calc.js 모듈 파일 

var Calc = function(start) {
	var that = this;
	
	this.add = function(x) {
		start = start +x;
		return that;
	};

	this.multiply = function(x) {
		start = start * x;
		return that;
	};

	this.equals = function(callback) {
		callback(start);
		return that;
	};
}
// module.exports를 사용한다 
module.exports = {
	add: function(x, y) {
		return new Calc(x).add(y || 0);
	},
	multiply: function(x, y) {
		return new Calc(x).multiply(y || 1);	
	}
}


- app.js 모듈 파일 

// require를 호출하여 모듈 즉, 컴포넌트를 로딩한다
var Calc = require('./calc.js');

// 모듈에서 외부로 노출시킨 API를 호출한다
Calc.add(1, 2)
	.multiply(3)
	.equals(function (result) {
		console.log(result);
	});



2) 브라우져 기반 모듈

  - Require.js 를 -AMD(Asynchronous Module Definition)- 사용한다 : Asynchronous 로딩이다

  - CommonJS와 약간의 차이가 있다

  - require 를 통해 dependencies와 callback을 얻는다 : 주로 호출하는 Main 입장의 application에서 사용할 때 

  - define 을 통해 dependencies를 얻고 API를 노출한다 : 개별 모듈을 정의할 때  

  - RequireJS사용하기 블로그

  - 제품 리스트를 보여주는 메인 소스 

//require 사용
require(['jquery', './big-cart'], function($, bigCart) {  <=== big-cart.js 의 펑션을 호출한다. 즉, big-car.js에 의존관계
	$(document).ready(function() {
		bigCart.init();
	});
})


  - 쇼핑 카트 

// define 사용하여 정의
define(['./pubsub', 'jquery'], function(pubsub, $) {  <=== pubsub.js 의 펑션을 호출한다. 즉, pubsub.js에 의존관계
	var cart, count = 0;

	pubsub.sub('add-to-cart', function(itme) {
		count++;

		cart.find('h1').html(count);

		var li = $('< li >')
			.html(item.name)
			.data('key', item.id);

		cart.find('ul').append(li);

	});

	pubsub.sub('remove-from-cart', function(item) {
		count--;

		cart.find('h1').html(count);
		cart.find('li').filter(function() {
			return $(this).data('key') == item.id;
		}).remove();

	});

	return {
		init: function() {
			cart = $('.big-cart');
		}
	}
});


  - 카트 내역 관리 모델 

define(function() {  <=== 의존하는 것이 없다 
	var cache = {};
	return {
		pub: function(id) {
			var args = [].slice.call(arguments, 1);
			if(!cache[id]) {
				cache[id] = [];
			}

			for(var i=0, il=cache[i].length; i -1) {
					cache[id] = cache[id].slice(0, index).concat(cache[id].slice(index+1));
				}
			}
		}
	}
});



3) CommonJS와 Require.js 개념 정리


4) AMD 개념


5) AMD 동영상
  - 하나의 자바스크립트 파일의 내역을 재사용할 수 있도록 - DRY (Don't Repeatly Yourself) - 모듈로 분리함
    + 첫째는 단순히 <script> 태그를 사용하여 개발자가 순서대로 넣는 호랑이 담배피던 시절의 방식
    + 둘째는 define을 사용하여 모듈라이제이션하고 사용시에 require 한다 
  - part01
 


posted by 윤영식
2013. 1. 13. 12:42 NodeJS/Modules

Socket.io안에서 사용되는 WebSocket 에 대한 프로토콜의 위치에 대하여 알아보자.


1) WebSocket 등장배경

  - 처음엔 iframe을 활용

  - 그다음은 XMLHTTPRequest를 이용

  - HTML5에 와서 Websocket 등장

  - SPDY 포로토콜을 통한 전송 압축 (성능향상)

  - Server Send Events (SSE)에 대한 이해


2) SPDY 프로토콜 등장배경

  - 실시간 Push 효과적 (압축 및 암호)

  - Node-SPDY 

  - Chrome/Firefox 지원


  - chrome://net-internals/#spdy  명령을 통해서 Chrome의 다양한 통신 내역을 살펴볼 수 있다.


3) 결론
  - Chrome이나 Firefox에서만 구동 될 수 있는 솔루션을 만들경우
  - Real-time Push 서비스를 할 경우 성능을 높이기 위해 사용
  - Node.js를 사용할 경우도 지원 


posted by 윤영식
2012. 11. 23. 16:28 NodeJS/Modules

prototype.js는 AJAX(Asynchronous JavaScript and XML)에서 거의 표준 라이브러리 처럼 사용하는 라이브러리이다. 사용법을 알아보자. 하기 코드는 prototype.js를 사용했을 때 JavaScript 클래스를 만들고 객체화 하는 과정을 보여준다 


var Employee = Class.create(); // Class를 이용하여 클래스 생성 Employee.prototype = { initialize : function( name ){ // prototype.js 사용시 생성자는 initialize로 정의 this.name = name } }; var Dev = Class.create(); Dev.prototype = Object.extend( // Class 상속 extend 이용 new Employee, // 상속받을 Class 선언 { showMember : function() { var list = new Array( '홍길동', '고길동', '김길동' ); document.writeln( '<div id="표시영역">' + this.name + '★사원 명단:' + list + '</div>' ); } } ); var dev = new Dev( '개발부' );

dev.showMember();


<참조>

  - 공식 사이트 :  http://prototypejs.org (버전 1.7.1)

  - 클래스 생성, 상속, Ajax 통신, JSON(JavaScript Object Notation) 사용 튜토리얼 :  http://prototypejs.org/learn/

  - prototype.js 정의 보기 :  https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js 

  - ExtJS를 하기 전 참조지만 JavaScript 하기전 기본지식과 Aptana+Spket 개발환경 설정하기 : http://techbug.tistory.com/1

  - 애니메이션과 Drag에 좋은 라이브러리 :  http://madrobby.github.com/scriptaculous



posted by 윤영식
2012. 10. 30. 19:24 NodeJS/Modules



CoffeeScript는 Javascript 코드를 단축시키고 가독성을 높이며 {}와 ; 가 있는 코드로 부터 해방시켜준다. 실제 CoffeeScript 코드를 보았을 때 마치 영어 산문을 보는듯 했다. 만일 마틴파울러 아저씨가 이야기하는 Clean Code Style을 지향한다면 정말 영어 산문을 쓰는듯 코딩을 하면 된다. 


1) CoffeeScript 코드 짜고 JavaScript와 비교하기 

  - http://coffeescript.org/#top 로 들어가서 "TRY COFFESCRIPT" 상단 메뉴를 선택한다. 브라우저에서 coffeescript 코드를 치면 바로 javascript코드로 확인할 수 있다.


  - 그렇다면 이런 coffeescript 코드를 어떻게 배울 수 있을까? 구글에서 "smooth coffeescript"를 검색하고 interactive... 을 선택한다

  
HTML5 화면으로 웹상에서 CoffeeScript를 익히면서 학습을 할 수 있는 사이트이다. Edit 박스의 코드를 수정하면 하단의 결과값이 자동 변경되어 출력된다. 
CoffeeScript 디버깅툴이 내장된 상용툴을 사용해 보자 (http://www.jetbrains.com/webstorm/)


<국내 레퍼런스> 

  - coffeescript 개념부터 잘 정리된 사이트 : http://aroundck.tistory.com/958

posted by 윤영식
prev 1 next