Node.js

[node.js] require() 그리고 module.exports

behonestar 2015. 5. 5. 14:24
개념

노드는 require()와 module.exports를 사용하여 필요한 자바스크립트 파일을 불러온 뒤 참조하거나 호출한다.

  1. 노드에서 하나의 자바스크립트 파일은 하나의 모듈이 된다.
  2. 자바스크립트 파일내에서 정의한 객체는 기본적으로 파일 내부에서만 접근할 수 있다.
  3. 함수 또는 변수를 module.exports에 할당하면 외부에서도 접근할 수 있다.


예제

user_module.js


var something = module.exports = function(name, age) {
    this.name = name;
    this.age = age;
    this.about = function() {
        console.log(this.name +' is '+ this.age +' years old');
    };
};


demo.js


var usermodule = require('./user_module');


설명

demo.js에서 user_module.js 파일을 불러와서 usermodule 변수에 할당하면 something 변수와 같은 객체를 참조한다.

var something = module.exports = {} 대신 exports = {} 또는 exports = someting = {}도 가능하다.


주의사항

최초 require()된 파일의 코드는 바로 실행되고 메모리에 캐싱된다. 이후 같은 파일을 require()하면 캐싱된 코드를 돌려주기만 하고 코드가 다시 실행되지는 않는다. 내부에서 상태를 갖거나 별도의 인스턴스가 필요하다면 초기화 함수를 따로 노출하거나 function을 리턴해 new로 인스턴스를 생성하여 사용해야 한다.


참고자료


  1. http://www.hacksparrow.com/node-js-exports-vs-module-exports.html
  2. https://opentutorials.org/module/938/7190
  3. NODE.JS 프로그래밍, 변정훈 지음


'Node.js' 카테고리의 다른 글

[node.js] HTTP Digest 인증  (0) 2015.05.09
[node.js] 이벤트  (0) 2015.05.05
[node.js] HTTP 동시 접속 성능 테스트  (0) 2015.05.05
[node.js] 특징  (0) 2015.05.05
[node.js] 시작하기  (0) 2015.04.20