module.exports and exports 모듈 확장

NodeJs 의 module.exports and exports 비교

모든 메서드가 들어있는 NodeJs App.js 파일이 점점 길어짐으로 보고
파일 하나의 길이로 세계신기록을 ;; 세우는 명예로운 일이 생기기 전에 
모듈화하는 방법을 찾다가 예전에 사용했던 Jquery plugIn 모듈화 방법이 떠올라
NodeJs에서도 사용 할 수 있을지 테스트 해보았다.

module.exports 를 이용한 확장.


app A


// Construct CallPlugin class 
var CallPlugin = require('./callPlugin');// fileName : callPluin.js for ModuleB
var callPlugin = new CallPlugin();
callPlugin.cmd('show');


module A


var CallPlugin = function(){
         console.log('CallPlugin is called'); 
}
var methods = {
    show: function(){
         console.log('CallPlugin > called hide'); 
    },
    hide: function(){
         console.log('CallPlugin > called hide'); 
    }
};
CallPlugin.prototype.cmd = function(method, opts) {
    return methods[method].call(null, opts);
}
module.exports = CallPlugin;

exports 를 이용한 확장.


app B

var callPlugin = require('./callPlugin'); // fileName : callPluin.js for ModuleB
callPlugin.cmd('show')


module B


var methods = {
    show: function(){
         console.log('CallPlugin > called hide'); 
    },
    hide: function(){
         console.log('CallPlugin > called hide'); 
    }
};

var cmd = function(method, opts) {
    return methods[method].call(null, opts);
}

exports.cmd = cmd;


위에서 처럼 두가지 방법으로 모듈을 제공할때
module B 방법처럼 exports 를 바로 사용해서 App에 사용하는 경우
라인의 수가 줄어들기 때문에 보다 적은 코딩 리소스로 모듈을 사용 할 수 있겠다.
(Module A와 비교해보면 new 를 사용한 생성 필요없음)

단, method Name에 대한 API 정의서 공유는 빠져서는 안되겠다.
그럼 메모리상

참고링크




댓글

가장 많이 본 글