본문 바로가기
IT/node.js

Node.js module.exports

by 뉴코딩맨 2023. 4. 27.
Node.js는 모듈 시스템을 사용하여 코드의 재사용성과 유지 보수성을 향상시키고, 큰 규모의 프로젝트에서 코드를 구성하는 방법을 단순화하는 기능을 제공합니다. 모듈은 파일로 구성되어 있으며, 파일 내부의 변수, 함수 또는 클래스 등을 다른 파일에서 사용할 수 있도록 내보내는 방법을 제공합니다. 이러한 기능을 구현하는 데 사용되는 메서드가 module.exports 입니다.
 
module.exports는 Node.js에서 모듈을 내보내는 방법 중 하나입니다. 이를 통해 모듈 파일 내부의 변수, 함수 또는 클래스 등을 다른 파일에서 사용할 수 있도록 내보낼 수 있습니다. module.exports는 일반적으로 객체 또는 함수를 반환하는 것이 일반적입니다.
 
모듈을 사용하면 다른 파일에서 해당 모듈을 require 함수를 사용하여 불러올 수 있습니다. require 함수를 사용하여 모듈을 불러오는 경우 해당 모듈의 내보낸 변수, 함수 또는 클래스 등을 사용할 수 있습니다.
 

 

 

사용법

 

예를 들어, 다음과 같이 example.js 파일을 생성합니다.
 
const exampleVariable = "Hello, World!";

function exampleFunction() {
	console.log("This is an example function.");
}

module.exports.exampleVariable = exampleVariable;
module.exports.exampleFunction = exampleFunction;
 
위 코드에서는 exampleVariable과 exampleFunction 변수를 module.exports 객체에 할당하여 내보내고 있습니다. 이제 app.js 파일에서 example.js 모듈을 불러와 해당 모듈에서 내보낸 변수와 함수를 사용할 수 있습니다.

 

 
const exampleModule = require("./example.js");
console.log(exampleModule.exampleVariable); // "Hello, World!"
exampleModule.exampleFunction(); // "This is an example function."
 
require 함수를 사용하여 example.js 모듈을 불러온 후, exampleVariable과 exampleFunction 변수에 접근할 수 있습니다. 이러한 방식으로 module.exports를 사용하여 모듈을 내보내고, require 함수를 사용하여 해당 모듈을 불러오면 다른 파일에서 해당 모듈의 변수, 함수 또는 클래스 등을 사용할 수 있습니다.
 
Node.js에서는 module.exports를 사용하여 객체, 함수, 클래스 등을 내보내는 방법을 제공합니다. module.exports를 사용하여 내보낼 수 있는 객체 또는 함수 등의 유형은 거의 무제한입니다. 따라서 module.exports는 Node.js에서 모듈 시스템을 사용하는 데 있어 중요한 개념 중 하나입니다.
 

'IT > node.js' 카테고리의 다른 글

Node.js package.json  (0) 2023.04.29
Node.js npm 이란?  (0) 2023.04.28
Node.js fs 모듈 사용법  (0) 2023.04.27
Node.js process.argv  (0) 2023.04.26
Node.js 파일 실행 방법  (0) 2023.04.26

댓글