728x90
반응형
1. 글로벌 객체란
글로벌 객체는 Node.js 어디서든 별도의 require 없이 사용할 수 있는 객체들입니다. 브라우저의 window 객체와 유사하게, Node.js는 global 객체를 최상위 스코프로 제공합니다. 하지만 모듈 시스템 특성상 var로 선언한 변수는 global에 추가되지 않습니다.
2. global 객체
// global 객체 확인
console.log(global);
// global에 속성 추가 (권장하지 않음)
global.myVar = 'Hello';
console.log(myVar); // Hello (어디서든 접근 가능)
// 브라우저의 window와 비교
// 브라우저: window.document, window.location
// Node.js: global.process, global.Buffer
3. 주요 글로벌 객체/함수
3.1 __dirname, __filename
현재 모듈의 경로 정보입니다. (CommonJS에서만 사용 가능)
// 현재 파일의 절대 경로
console.log(__filename);
// /home/user/project/app.js
// 현재 파일이 있는 디렉토리 경로
console.log(__dirname);
// /home/user/project
// ES Modules에서는 다르게 처리
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
3.2 console
표준 출력과 에러 출력을 위한 객체입니다.
console.log('일반 로그');
console.error('에러 로그');
console.warn('경고 로그');
console.info('정보 로그');
// 객체 출력
console.dir({ name: 'test', nested: { value: 123 } }, { depth: null });
// 테이블 형식 출력
console.table([
{ name: '홍길동', age: 30 },
{ name: '김철수', age: 25 }
]);
// 시간 측정
console.time('작업');
// ... 작업 수행
console.timeEnd('작업'); // 작업: 123.456ms
// 조건부 로그
console.assert(1 === 2, '1은 2가 아닙니다');
// 호출 스택 출력
console.trace('여기서 호출됨');
3.3 process
현재 Node.js 프로세스에 대한 정보와 제어를 제공합니다.
// 프로세스 정보
console.log(process.pid); // 프로세스 ID
console.log(process.version); // Node.js 버전
console.log(process.platform); // 운영체제 (darwin, win32, linux)
console.log(process.arch); // CPU 아키텍처 (x64, arm64)
console.log(process.cwd()); // 현재 작업 디렉토리
console.log(process.memoryUsage()); // 메모리 사용량
// 환경 변수
console.log(process.env.NODE_ENV);
console.log(process.env.PATH);
// 명령줄 인자
console.log(process.argv);
// ['node', '/path/to/script.js', 'arg1', 'arg2']
3.4 Buffer
바이너리 데이터를 다루는 클래스입니다.
const buf = Buffer.from('Hello');
console.log(buf); // <Buffer 48 65 6c 6c 6f>
console.log(buf.toString()); // Hello
3.5 타이머 함수
// 지정 시간 후 실행
const timeoutId = setTimeout(() => {
console.log('3초 후 실행');
}, 3000);
// 반복 실행
const intervalId = setInterval(() => {
console.log('1초마다 실행');
}, 1000);
// 현재 이벤트 루프 후 실행
setImmediate(() => {
console.log('즉시 실행 (이벤트 루프 다음)');
});
// 타이머 취소
clearTimeout(timeoutId);
clearInterval(intervalId);
4. 모듈 관련 글로벌
4.1 require, module, exports (CommonJS)
// 모듈 불러오기
const fs = require('fs');
const myModule = require('./myModule');
// 모듈 내보내기
module.exports = { name: 'test' };
exports.func = () => {};
// 모듈 정보
console.log(module.id); // 모듈 식별자
console.log(module.filename); // 파일 경로
console.log(module.loaded); // 로드 완료 여부
console.log(module.paths); // 모듈 검색 경로
4.2 require.resolve, require.cache
// 모듈 경로 확인 (로드하지 않음)
const modulePath = require.resolve('express');
console.log(modulePath);
// 캐시된 모듈 확인
console.log(require.cache);
// 캐시 삭제 (재로드용)
delete require.cache[require.resolve('./myModule')];
반응형
5. URL, URLSearchParams
WHATWG URL API가 글로벌로 제공됩니다.
const myUrl = new URL('https://example.com/path?name=test');
console.log(myUrl.hostname); // example.com
console.log(myUrl.searchParams.get('name')); // test
const params = new URLSearchParams('a=1&b=2');
console.log(params.get('a')); // 1
6. TextEncoder, TextDecoder
문자열과 바이너리 데이터 변환을 위한 API입니다.
// 문자열 → Uint8Array
const encoder = new TextEncoder();
const encoded = encoder.encode('Hello');
console.log(encoded); // Uint8Array(5) [72, 101, 108, 108, 111]
// Uint8Array → 문자열
const decoder = new TextDecoder();
const decoded = decoder.decode(encoded);
console.log(decoded); // Hello
7. 기타 글로벌
// 이벤트 처리
const eventEmitter = new EventEmitter(); // X - require 필요
// AbortController (Node.js 15+)
const controller = new AbortController();
const signal = controller.signal;
signal.addEventListener('abort', () => {
console.log('작업 취소됨');
});
controller.abort();
// queueMicrotask
queueMicrotask(() => {
console.log('마이크로태스크');
});
// structuredClone (Node.js 17+)
const obj = { a: 1, b: { c: 2 } };
const clone = structuredClone(obj);
8. globalThis
ES2020에서 도입된 환경 독립적인 전역 객체 참조입니다.
// 브라우저: globalThis === window
// Node.js: globalThis === global
// Worker: globalThis === self
console.log(globalThis === global); // true (Node.js)
// 환경에 관계없이 동작하는 코드
globalThis.myGlobal = 'value';
결론
Node.js의 글로벌 객체는 require 없이 어디서든 사용할 수 있는 내장 객체들입니다. global, process, console, Buffer, 타이머 함수(__dirname, __filename 등)가 대표적입니다. global 객체에 변수를 추가하는 것은 권장되지 않으며, 모듈 시스템을 통한 명시적인 의존성 관리가 좋은 방식입니다.
728x90
반응형
'Node.js' 카테고리의 다른 글
| Node.js의 버퍼(Buffer) 사용법 (0) | 2026.02.24 |
|---|---|
| Node.js의 스트림 모듈(stream module) (0) | 2026.02.24 |
| Node.js의 이벤트 모듈(events module) (0) | 2026.02.24 |
| Node.js의 경로 모듈(path module) (0) | 2026.02.23 |
| Node.js의 URL 모듈(url module) (0) | 2026.02.23 |