Will find a way

[NodeJs] 모듈, require, module.exports와 exports 본문

BackEnd/NodeJs

[NodeJs] 모듈, require, module.exports와 exports

Jaka_Park 2024. 6. 5. 20:32

 

목차

1. 모듈이란?

2. require

3. module.exports / exports 

 

1. 모듈이란?

- 모듈은 특정한 기능을 하는 함수나 변수들의 집합으로 프로그램의 가장 작은 단위(모듈)를 의미한다.

- 만약 하나의 파일에 기능의 내용을 모두 작성하면 유지보수도 힘들고 변수명도 겹치기도 하는데 이를 방지하는데 유용하다.

 

2. require

NodeJs 에서 require 메서드를 통해 외부 모듈을 가져올 수 있다.

형태는 괄호 안에 파일의 경로를 넣는데 다음과 같다.

const a = require("./index") 
// index는 파일의 이름이고
// js파일의 js는 생략이 가능하다

 

3. module.exports 와 exports

1) module.exports

module을 내보낼 때 사용.

 

index2.js

const product = {
  name : "맥북",
  year : 2022,
  comment(){
    console.log("애플 제품이에요")
  }
}

module.exports = product;
// module.exports = product;
// index2.js 파일에서 내보낼 데이터 / 반환되는 데이터

 

index3.js

// require 외부 모듈을 가져올 때 사용
const mac = require("./index2");

console.log(mac);

 

<결과값>

 


2) exports

module을 내보낼 때 사용

 

index1.js

// global 전역객체
// module 생략가능
exports.product = {name : "맥북"}

 

index2.js

// product의 key 값으로 구조분해할당 가능
const {product} = require("./index1");
console.log(product)

 

결과창

 

 

위에서 module.exports 와 exports 의 차이를 보면 module.exports 에서 exports 빈객체이기 때문에 key 값으로 접근이 불가능하고 exports는 점접근법을 사용함으로서 빈객체 안에 key값이 담긴 객체가 담겨있다. 이 말은 즉 exports는 key 값으로 value를 접근할 수 있다는 것을 의미하며 구조분해할당이 가능하다.

 

'BackEnd > NodeJs' 카테고리의 다른 글

스트림(Stream) 사용 예제  (0) 2024.06.12
버퍼 (Buffer) / 스트림 (Stream)  (1) 2024.06.11
TCP 서버 간단하게 구현하기  (0) 2024.06.10
[NodeJs] REPL 모드  (0) 2024.06.04
NodeJs 첫 시작  (0) 2024.06.04