node.js 모듈

웅평·2023년 7월 18일
0

모듈 가져오기

main.js

let m = require('./math.js');

console.log(m.add(1, 2));

math.js

function add(a, b) {
    return a + b;
}

main.js에서 math.js의 함수 add를 가져와 실행하려면 require를 통해 경로를 지정해야한다.
하지만 이대로 실행하면 에러가 발생한다

모듈 내부의 것들을 외부로 공개해줘야 다른 모듈에서도 사용 가능하다. math.js의 add함수를 공개하지 않아서 발생한 에러이다

이 문제를 해결하려면 exports를 사용하면 된다. export는 우리말로 내보내다 라는 뜻이다

math.js

function add(a, b) {
    return a + b;
}

exports.add = add;

exports.add = add;를 추가혀여 실행하면 오류가 발생하지 않는다.
해석하면 모듈안에 있는 add함수를 모듈 외부에도 add라는 이름으로 공개한다는 것이다.
exports.plus = add; 라고 한다면 add함수를 모듈 외부에 plus라는 이름으로 공개한다는 것이다.

여러 모듈 모아서 공개

math.js

function add(a, b) {
    return a + b;
}

const PI = 3.14;
let user = 'kim'

let test = {
    name: 'som',
    tem: ['a', 'b'],
    printType() {
        for (const i in this.types) {
            conseol.log(this.types[i]);
        }
    }
};


exports.add = add;
exports.PI = PI;
exports.user = user;
exports.test = test;

하나씩 exports하는 방법도 있지만 모아서 공개하는 방법은 공개하고 싶은것들을 모아서 하나의 객체로 만들고 module.exports로 객체를 공개한다

let cal = {
    add: function(a, b) {
        return a + b;
    },
    PI: 3.14,
    user: 'kim',
    
    test: {
        name: 'som',
        tem: ['a', 'b'],
        printType() {
            for (const i in this.types) {
                conseol.log(this.types[i]);
            }
        }
    }
};

module.exports = cal;

Module wrapper function

Node.js가 모듈을 로드할 때 Module wrapper function이라는 것으로 모듈 내의 전체 코드를 감싸주는 작업이 있다. 모듈을 감싸주는 코드를 의미한다

(function (exports, require, module, __filename, __dirname) {
  // 모듈 코드
});

위의 코드가 math.js 모듈을 로드할 때

function add(a, b) {
  return a + b;
}

exports.add = add;

위의 코드를 아래 코드처럼 감싸준다.

(function (exports, require, module, __filename, __dirname) {
  function add(a, b) {
    return a + b;
  }
  exports.add = add;
});

exports, require, module, filename, dirname이 다섯가지 인자는 접슨이 가능하다

function add(a, b) {
  return a + b;
}

console.log('exports ------------------------->');
console.dir(exports);
console.log('require ------------------------->');
console.dir(require);
console.log('module ------------------------->');
console.dir(module);
console.log('__filename ------------------------->');
console.dir(__filename);
console.log('__dirname ------------------------->');
console.dir(__dirname);

이 코드를 실행하면 여러가지 정보가 출력된다.

정리
(1) Node.js는 모듈을 로드하기 전에 그 전체 코드를 Module wrapper function이라는 것으로 감싸준다.
(2) Module wrapper function은 그 5개의 인자에 각각 적절한 값이나 객체를 설정해주는데
(3) 우리가 모듈 내의 코드에서 exports 인자로 넘어와서 그 프로퍼티를 하나씩 채워나가는 객체(또는 module 인자의 exports 프로퍼티로 설정되는 객체)가
(4) 다른 모듈에서 이 모듈을 require 함수로 로드했을 때 리턴되는 객체이다.

참고
코드잇

0개의 댓글