The Pursuit of Happyness

반응형

실행환경 Ubuntu 14.04 LTS / node v0.10.25


이번에는 유저가 정의한 모듈을 사용하는 예제이다.

살펴볼 예제는 세율을 설정하고 아이템 가격을 입력하면 세금을 포함한 가격을 계산해 주는 모듈이다.


먼저 lib 라는 폴더를 만들고 거기에 tax.js라는 파일을 생성하여 다음과 같이 코딩한다.

var _taxRate = 0.10;

function roundTwoDecimals(amount) {
        return Math.round(amount*100) / 100;
}

exports.getTaxRate = function() {
        return _taxRate;
}

exports.setTaxRate = function(taxRate) {
        _taxRate = taxRate;
}

exports.calcTotalAmount = function(price) {
        return roundTwoDecimals( (1 + _taxRate) * price );
}

tax 라는 모듈을 이용해서 실행할 예제이다. moduletest.js 라는 파일을 만들어서 다음과 같이 코딩하자.

var tax = require('./lib/tax');
tax.setTaxRate(0.09);

var itemPrice = 10.00;
console.log("Tax Rate     :  " + (tax.getTaxRate()*100).toFixed(2) + "%");
console.log("Item Price   : $" + itemPrice.toFixed(2));
console.log("Total Amount : $" + (tax.calcTotalAmount(itemPrice)).toFixed(2));


nodejs moduletest 라고 실행하면 결과가 출력된다.

모듈을 만들 때 외부에서 접근이 가능하게 하기 위해서는 "exports" 로 정의해야 하며,

exports를 사용하지 않고 정의된 function 은 외부에서 사용이 불가능하다.

반응형