Node.js 환경에서 require()
메서드를 통해 모듈을 가져올 수 있다.
// math.js 파일
const add = (a, b) => {
return a + b;
};
const subtract = (a, b) => {
return a - b;
};
module.exports = { add, subtract };
// index.js 파일
const math = require('./math');
const sum = math.add(5, 3);
console.log('Sum:', sum); // 출력: Sum: 8
const difference = math.subtract(10, 4);
console.log('Difference:', difference); // 출력: Difference: 6
math.js
라는 모듈을 index.js
에서 가져와서 사용하는 예제이다.math.js
내에 있는 add
와 subtract
함수를 require()
를 사용하여 결과를 출력하는 코드이다.require('./math');
는 현재 디렉토리에 있는 math.js
파일을 가져온다는 의미.// Express 프레임워크도 가져올 수 있다.
const express = require("express");
이런식으로 외부모듈이나 파일들을 require()
를 통해 모듈 또는 라이브러리, 프레임워크를 가져오고 이것들을 변수에 할당하여 사용이 가능하다.