본문 바로가기
Do it Node.js/EJS BackEnd

3. 모듈 시스템

by 갱생angel 2024. 2. 24.

모듈 : 프로그램을 최대한 작은 기능 단위로 나누고 파일 형태로 저장한 것

  -CommonJS 모듈 시스템 : require 함수를 통해 모듈을 사용, 현재 가장 많이 사용

  -ES 모듈 시스템 : 에크마스크립트가 발전하면서 모듈을 처리

 

ch02 - <user.js>, <hello.js>, <app.js> : CommonJS 모듈 시스템 사용

  -module.exports : 모듈을 외부로 내보내는 명령어

  -require() : 모듈을 가져오는 함수

//user.js
const user1 = "Kim";
const user2 = "Lee";
const user3 = "Choi";

module.exports = { user1, user2, user3 }; //user1, user2, user3을 외부로 내보냄
//hello.js
const hello = (name) => {
  console.log(`${name} 님, 환영합니다.`);
};

module.exports = hello; //hello 함수를 외부로 내보냄
//app.js
const { user1, user2, user3 } = require("./user"); //user1, user2, user3을 가져옴
const hello = require("./hello"); //hello 함수를 가져옴

hello(user1);
hello(user2);
hello(user3);
>> node app

 

  -객체 형식으로 받기

//app.js
const user = require("./user");
const hello = require("./hello");

console.log(user);
hello(user.user3); //객체 형식으로 받기
>> node app


코어 모듈 : 이미 내장되어 있는 백엔드 개발에 필요한 모듈

  -node:접두사 : 코어 모듈이라는 사실을 명확히 보여줌 ex) const fs = require('node:fs')

글로버(global) 모듈 : require 함수 없이 그대로 사용할 수 있는 모듈, global은 생략 가능

  -__dirname : 현재 모듈이 있는 폴더 이름

  -__filename : 현재 모듈이 있는 파일 이름

 

ch02 - <here.js>

console.log(`현재 모듈이 있는 폴더 이름 : ${__dirname}`);
console.log(`현재 모듈이 있는 파일 이름 : ${__filename}`);
>> node here


ch02 - <say.mjs>, <app.mjs> : ES 모듈 시스템 사용

  -export default : 모듈을 외부로 내보내기

  -import ~ from : 모듈을 가져오기

//say.mjs
const hi = (name) => {
  console.log(`${name} 님, 안녕하세요.`);
};

const goodbye = (name) => {
  console.log(`${name} 님, 안녕히 가세요.`);
};

export default { hi, goodbye }; //모듈을 외부로 내보냄
//app.mjs
import say from "./say.mjs"; //모듈을 가져옴

say.hi("홍길동");
say.goodbye("이순신");
>> node app.mjs

 

'Do it Node.js > EJS BackEnd' 카테고리의 다른 글

6. 버퍼, 스트림, 파이프  (0) 2024.02.28
5. fs 모듈  (0) 2024.02.27
4. path 모듈  (0) 2024.02.25
2. 자바스크립트 비동기 처리  (0) 2024.02.23
1. node.js, npm  (0) 2024.02.22