npm에는 다양한 모듈들이 존재 한다 예를 들어
// Express 프레임워크를 사용하여 웹 서버를 생성하기 위해 express를 불러옵니다.
const express = require('express');
// 파일 및 디렉토리 경로를 다루기 위해 Node.js의 path 모듈을 불러옵니다.
const path = require('path');
// MongoDB 데이터베이스와 연결하기 위해 mongoose를 불러옵니다.
const mongoose = require('mongoose');
// EJS 템플릿 엔진을 확장하기 위해 ejsMate를 불러옵니다.
const ejsMate = require('ejs-mate');
// 세션 관리를 위해 express-session을 불러옵니다.
const session = require('express-session');
// 사용자에게 일시적인 메시지를 전달하기 위해 connect-flash를 불러옵니다.
const flash = require('connect-flash');
// 사용자 정의 오류 핸들링을 위해 ExpressError 클래스를 불러옵니다.
const ExpressError = require('./seeds/utils/expressError');
// HTML 폼에서 PUT, DELETE 등의 메서드를 사용할 수 있게 해주는 method-override를 불러옵니다.
const methodOverride = require('method-override');
// 인증을 처리하기 위해 passport를 불러옵니다.
const passport = require('passport');
// 로컬 전략을 사용하여 인증을 구현하기 위해 passport-local을 불러옵니다.
const LocalStrategy = require('passport-local');
// 사용자 모델을 불러와서 Passport와 통합합니다.
const User = require('./models/user');
// 보안 강화를 위해 HTTP 헤더를 설정하는 helmet을 불러옵니다.
const helmet = require('helmet');
이러한 것 들이 존재하며
require 키워드를 사용하여 변수를 할당하고 모듈을 불러오는 방식이다. require는
모듈을 가져오는 방식이라 할 수 있다.
ex-
person.js를 만들고
const we = ['i','you']
module.exports = we
index.js에서 해당 모듈을 사용하면
const we = require('./we')
console.log(we)
node index.js를 하게 되면
['i','you']라는 결과 같이 출력되며
여러번의 모듈을 호출하여 사용하면
const we1 = require('./we')
const we2 = require('./we')
console.log(we1 === we2)
결과는 true 라고 찍히게 된다
모듈을 각각 require하여 다른 변수에 담았는데도 같다고 나오는 이유는
이 파일은 딱 한번만 실행되어 동일한 객체로 사용된다는 것이다.
즉 require를 할 때마다 파일이 실행되는 것이 아니다.
이러한 모듈을 내보내는 방식은 2가지가 있다.
1.여러 객체를 내보낼 때는 exports의 속성으로 할당한다.
2.하나의 객체를 내보낼 때는 module.exports에 할당한다.
ex-
// 여러 객체를 내보낼 때
exports.a = 1;
exports.b = 2;
exports.c = 3;
// 하나의 객체를 내보낼 때
const obj = {
a: 1,
b: 2,
c: 3
};
module.exports = obj;
모듈에서 내보내지는 데이터를 담고 있는 객체가 exports이기 때문에 이렇게 하는것이다.
exports 와 module.exports 객체는 동일하지만 exports가 modeul.exports객체를
참조하고 있으며 최종적으로 리턴하는 값은 module.exports다.
참조