WEB-STUDY
node.js의 모듈
비숑주인
2025. 1. 10. 21:12
모듈
프로그램을 작은 기능 단위로 쪼개고 파일 형태로 저장해 놓은 것
코드를 중복해서 작성하지 않아도 된다
수정이 필요할 경우 필요한 모듈만 수정하면 된다.
CommonJS 모듈 시스템 vs ES 모듈 시스템
- CommonJS 모듈 시스템: Node.js의 기본 모듈 시스템. (require, module.exports 사용)
- ES 모듈 시스템: ECMAScript의 표준 모듈 시스템. (import, export 사용)
- Node.js에서 ES 모듈 시스템 지원
모듈 만들기
// user.js
const user = "홍길동";
module.exports = user;
// hello.js
const hello = (name) => {
console.log(`${name}님, 안녕하세요?`);
};
module.exports = hello;
// app.js
const user = require("./user");
const hello = require("./hello");
hello(user);
만약 일부 값만 내보내고 싶으면 아래처럼 하면 된다.
// user-1.js
const user1 = "Kim";
const user2 = "Lee";
const user3 = "Choi";
module.exports = { user1, user2 };
// app.js
const { user1, user2 } = require("./user-1");
node 코어 모듈
nodejs.org > Docs > API에 node.js에서 제공하는 모듈들을 볼 수 있다.
CJS는 Node.js에서 기본적으로 사용하는 모듈 시스템이다. (require문을 사용)
노드 코어 모듈 – 글로벌 모듈
- 글로벌 모듈: require 없이 사용할 수 있는 모듈
- 글로벌 객체: 글로벌 모듈에 있는 객체
// console 객체의 log 함수 사용
global.console.log(`${name}님, 안녕하세요?`);
// 글로벌은 코드 어디에서나 사용할 수 있어서 global을 생략하고 간단히 사용할 수 있음
console.log(`${name}님, 안녕하세요?`);
- 글로벌 모듈의 특징:
- 노드 환경에서 기본적으로 제공되며, require 없이 바로 사용 가능하다.
- 예: console, setTimeout, setInterval, process, __dirname, __filename 등.
- global 객체:
- Node.js의 글로벌 객체는 브라우저의 window 객체와 유사하다.
- 모든 글로벌 변수와 함수는 global 객체의 프로퍼티로 접근할 수 있다.
- 예: global.console, global.setTimeout
// console.log(`현재 모듈의 파일명: ${__filename}`);
console.log(`현재 모듈이 있는 폴더: ${__dirname}`);
console.log(`현재 모듈의 파일명: ${__filename}`);
- __dirname과 __filename은 Node.js 환경에서만 동작합니다. 브라우저에서는 사용할 수 없다.
- ES 모듈(.mjs)을 사용할 경우, 기본적으로 __dirname과 __filename이 정의되지 않습니다. 이를 해결하려면 아래와 같이 작성해야 한다.
import { dirname } from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
노드의 주요 글로벌 객체
글로벌 | 객체 설명 |
console | 콘솔 출력 (예: console.log) |
setTimeout | 일정 시간 후에 함수를 실행 |
setInterval | 일정 시간 간격으로 함수를 반복 실행 |
process | 현재 실행 중인 노드 프로세스 정보 제공 |
__dirname | 현재 실행 중인 파일의 디렉터리 경로 |
__filename | 현재 실행 중인 파일의 전체 경로 |
path 모듈
path 모듈이 왜 필요할까
- 경로 구분자를 통일할 수 있다.
- 운영 체제에 따라 파일 경로 구분자가 다름:
- Windows: 역슬래시(\) 사용
- 예: C:\Users\funco\Desktop\myNode\basics\03\example.txt
- macOS / Linux: 슬래시(/) 사용
- 예: /Users/funnycom/Desktop/basics/03/example.txt
- Windows: 역슬래시(\) 사용
- 운영 체제에 따라 파일 경로 구분자가 다름:
- 경로를 나누거나 합칠 수 있다.
- 절대 경로:
- 서버에서 파일 경로를 지정할 때 주로 사용.
- 예: /var/www/html/index.html 또는 C:\Projects\index.html
- 상대 경로:
- 프로젝트 내부 파일 간 접근에 주로 사용.
- 예: ./src/utils.js 또는 ../config/config.json
// path 모듈 연습하기 (결과 비교 파일: 03\results\path.js)
const path = require("path");
// join
const fullPath = path.join('some', 'work', 'ex.txt');
console.log(fullPath);
// 경로만 추출 - dirname
const dir = path.dirname(fullPath);
console.log(dir);
// 파일 이름만 추출 - basename
const fn1 = path.basename(__filename);
console.log(`전체 경로(__filename): ${__filename}`);
console.log(fn1);
require (path)으로 path 모듈을 가지고 오면 path 모듈 안에 있는 join 함수, dirname 함수, basename 함수들을 가져와서 사용할 수 있다.
File System Module
동기식 함수 (Synchronous) 와 비동기식 함수 (Asynchronous) 를 따로 구분해서 제공
비동기식 같은 경우 Callback과 Promises 중 선택 해서 사용할 수 있다.
// fs 모듈의 readdir 함수 연습하기 (결과 비교 파일: 03\results\list-2.js)
const fs = require("fs");
fs.readdir(".", (err, files) => { // 특정 디렉터리의 파일 및 디렉터리 목록을 읽어온다.
if (err) {
console.log(err);
}
console.log(files);
});