[require(), exports / module.exports] Node.js study

김승훈·2020년 5월 2일
0

모듈이란 "독립된 기능을 갖는 것(함수, 파일)들의 모임"이라고 이해하시면 좋을 것 같습니다.

require(); //모듈 불러오기

const express = require("express"); //외장 모듈
const index = require("./index.js"); //js파일은 .js 를 안붙이고 -> index만 써두된다.
//내장 모듈

-외장 모듈은 npm(Node Package Manager)을 통해 모듈을 다운받아야 합니다. 다운로드 후 내장모듈처럼 require해서 사용할 수 있습니다.

node.js는 require 메소드를 통해서 외부 모듈을 가지고 올 수 있다.
모듈을 불러오기 위해 require()함수를 사용

NPM 사용법

-npm을 사용하는 방법은 간단합니다. 커멘드 창에서 " npm install [모듈명] " 을 입력하면 설치가 됩니다.

-모듈을 설치할 때 옵션을 줄 수 있습니다.

1) npm install [모듈명] -g : g는 global을 뜻하며 전역으로 모듈을 다운받는 것입니다. express같은 커멘트창에서 사용되어지는 모듈은 global하게 설치해야하기때문에 옵션으로 줍니다.

2) npm install [모듈명] --save : --save를 옵션으로 주게되면 모듈이 설치되면서 자동적으로 package.json을 업데이트 시켜줍니다. package.json 파일의 dependencied 부분이 업데이트되게 됩니다.

exports / module.exports //모듈 생성하기

exports vs module.exports

module.exports를 사용해서 객체를 할당해주는 것이 더 좋습니다.

exports는 module.exports를 참조합니다.
일반적으로 module.exports를 통해 모듈을 생성합니다.

  • module.exports는 require() 함수를 사용했을 때 반환 받는 변수라고 생각해봅시다. 비어 있는 객체가 기본값이며 어떤 것으로도 자유롭게 변경할 수 있습니다.

  • exports 자체는 절대 반환되지 않습니다! exports는 단순히 module.exports를 참조하고 있습니다. 이 편리한 변수를 사용하면 모듈을 작성할 때 더 적은 양의 코드로 작성할 수 있습니다. 이 변수의 프로퍼티를 사용하는 방법도 안전하고 추천하는 방법입니다.

module.exports하면 database_module함수를 함수처럼 호출 할 수 있습니다 required. 간단히 설정 exports하면 노드가 객체 module.exports참조를 내보내므로 함수를 내보낼 수 없습니다 .

exports

// greetings.js
var exports = module.exports = {};
// greetings.js
// var exports = module.exports = {};

exports.sayHelloInEnglish = function() {
    return "HELLO";
};
exports.sayHelloInSpanish = function() {
    return "Hola";
};

module.exports

module.exports = {
    sayHelloInEnglish: function() {
        return "HELLO";
    },

    sayHelloInSpanish: function() {
        return "Hola";
    }
};

module.exports 와 exports 는 call by reference 로 동일한 객체를 바라보고 있고, 리턴되는 값은 항상 module.exports 입니다.

참조

https://jongmin92.github.io/2016/08/25/Node/module-exports_exports/
https://stackoverflow.com/questions/7137397/module-exports-vs-exports-in-node-js
exports vs module.exports
require(), exports, module.exports 공식문서로 이해하기

0개의 댓글