[JavaScript] require()

민승기·2023년 11월 17일
0

JavaScript

목록 보기
24/24
post-thumbnail

require()

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
  1. math.js라는 모듈을 index.js에서 가져와서 사용하는 예제이다.
  2. math.js 내에 있는 addsubtract함수를 require()를 사용하여 결과를 출력하는 코드이다.
  3. require('./math'); 는 현재 디렉토리에 있는 math.js 파일을 가져온다는 의미.
// Express 프레임워크도 가져올 수 있다.
const express = require("express");

이런식으로 외부모듈이나 파일들을 require()를 통해 모듈 또는 라이브러리, 프레임워크를 가져오고 이것들을 변수에 할당하여 사용이 가능하다.

profile
개발자를 꿈꾸는 늙은이👨🏻‍💻

0개의 댓글