NODE.js는 자바스크립트 Runtime Environment로 주로 서버 사이드 애플리케이션 개발에 사용됩니다.
Node.js는 브라우저 외부 환경에서 자바스크립트 애플리케이션 개발에 사용되며 이에 필요한 모듈, 파일 시스템, HTTP 등 Built-in API를 제공합니다.
REPL은 입력, 수행, 출력의 과정을 반복하는 가상 환경으로, Node.js를 포함한 대부분의 언어(Java, Python 등)에서 제공됩니다. REPL 환경에서는 간단한 코드를 입력해 실행 결과를 즉시 확인할 수 있습니다.
터미널(윈도우에서는 명령 프롬프트)에서 node 명령어를 입력하면 REPL이 실행되며, 프롬프트가 >로 변경됩니다. 이 상태에서 Node.js 코드를 작성해 바로 실행해볼 수 있습니다. REPL을 종료하려면 CTRL + C 키를 두 번 누르면 됩니다.
Node.js 파일을 실행하려면 node 명령어 뒤에 파일명을 입력합니다. 파일 확장자 .js는 생략할 수 있습니다.
> 1 * 0
0
> x = 10
10
> console.log('Hello World')
Hello World
undefined
Node.js는 이벤트가 발생할 때마다 미리 지정해둔 작업을 수행하는 이벤트 기반 프로그래밍 방식을 사용합니다.
이러한 구조는 서버가 이벤트나 사용자 입력에 대해 빠르게 응답할 수 있도록 해줍니다.
Node.js는 I/O 작업을 비동기 방식으로 처리하므로, 오래 걸리는 함수는 백그라운드에서 실행되고 다음 코드가 먼저 실행됩니다.
작업이 완료되면 콜백 함수가 실행되며, 이를 통해 비동기 처리를 통한 성능 최적화를 제공합니다.

Node.js의 전역 객체로, 모든 모듈에서 접근할 수 있는 변수를 저장할 수 있습니다.
브라우저의 window 객체와 비슷한 역할을 합니다.
단, 너무 많은 전역 변수 사용은 가독성에 영향을 주고 오류 추적을 어렵게 할 수 있으므로 주의가 필요합니다.
global.appName = 'My App';
console.log(appName); // 'My App'
console.log('일반 로그'); // 일반 출력
console.error('에러 메시지'); // 에러 출력
console.warn('경고 메시지'); // 경고 출력
console.info('정보 메시지'); // 정보 출력
console.table([{ name: 'Node' }, { name: 'React' }]); // 객체 표 형태로 출력
console.time('timer'); // 타이머 시작
setTimeout(() => {
console.timeEnd('timer'); // 타이머 종료 및 경과 시간 출력
}, 500);
타이머를 통해 비동기 작업을 수행할 수 있습니다.
브라우저에서는 window 객체이지만, node에서는 global 객체에 들어가 있습니다.
setTimeout(() => console.log('2초 후 실행'), 2000);
let count = 0;
const interval = setInterval(() => {
console.log(`1초마다 실행: ${++count}`);
if (count === 5) clearInterval(interval); // 5회 후 중단
}, 1000);
setImmediate(() => console.log('이벤트 루프 종료 후 즉시 실행'));
__filename: 현재 파일의 절대 경로__dirname: 현재 디렉터리의 절대 경로const path = require('path');
const filePath = path.join(__dirname, 'data.json');
console.log(filePath); // /path/to/your/data.json
//모듈 내보내기
const greeting = 'Hello';
module.exports = { greeting };
//모듈 가져오기
const { greeting } = require('./a');
console.log(greeting); // 'Hello'
require는 다른 모듈이나 파일을 가져올 때 사용합니다.
const os = require('os'); // 내장 모듈
console.log(os.platform()); // 'win32' 또는 'linux'
const customModule = require('./customModule'); // 사용자 정의 모듈
console.log(customModule);
process는 현재 실행 중인 Node.js 프로세스에 대한 정보를 제공합니다.
시스템 환경 변수를 조회하거나 설정합니다.
process.env.NODE_ENV = 'development';
if (process.env.NODE_ENV === 'development') {
console.log('개발 모드');
} else {
console.log('프로덕션 모드');
}
명령줄 인수를 배열로 반환하여 CLI(Command Line Interface) 인수들을 사용할 수 있습니다.
명령줄에서 다음과 같이 인수를 전달할 수 있습니다.
node args.js hello world 42
이 명령을 실행하면 출력은 다음과 같이 나옵니다
console.log(process.argv);
/*
[
'/path/to/node', // Node.js 경로 (예: /usr/local/bin/node)
'/path/to/args.js', // 실행 중인 파일 경로
'hello', // 첫 번째 인수
'world', // 두 번째 인수
'42' // 세 번째 인수
]
*/
const args = process.argv.slice(2); // 첫 두 개 요소는 제외하고 가져옴
const numbers = args.map(Number); // 문자열을 숫자로 변환
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(`The sum is: ${sum}`);
다음 이벤트 루프 사이클에서 특정 함수를 실행합니다.
console.log('첫 번째');
process.nextTick(() => console.log('nextTick 실행'));
console.log('두 번째');
if (process.env.NODE_ENV !== 'production') {
console.error('개발 모드에서는 종료할 수 없습니다.');
process.exit(1); // 에러 코드 1로 종료
}
파일 읽기, 쓰기, 삭제 등 파일 시스템을 조작할 수 있는 기능을 제공합니다.
동기(fs.readFileSync) 및 비동기(fs.readFile) 방식으로 파일 작업을 할 수 있어, 블로킹과 논블로킹 방식 모두 지원합니다.
const fs = require('fs');
// 비동기 파일 읽기
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
HTTP와 HTTPS 서버 및 클라이언트를 구축할 수 있습니다.
REST API, 웹서버, 마이크로서비스 개발에 널리 사용됩니다.
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
파일 경로를 쉽게 조작할 수 있게 해주는 유틸리티 모듈입니다.
경로 합치기(path.join()), 경로 구분자 확인(path.sep), 확장자 추출(path.extname()) 등 파일 경로와 관련된 여러 유용한 기능을 제공합니다.
const path = require('path');
const filePath = '/user/local/bin/file.txt';
console.log('확장자:', path.extname(filePath)); // '.txt'
console.log('디렉터리명:', path.dirname(filePath)); // '/user/local/bin'
console.log('파일명:', path.basename(filePath)); // 'file.txt'
console.log('절대 경로:', path.resolve('bin', 'file.txt')); // /current/dir/bin/file.txt
console.log('경로 결합:', path.join('/user', 'local', 'bin')); // '/user/local/bin'
운영 체제와 관련된 유틸리티를 제공합니다.
시스템의 플랫폼, 아키텍처, CPU, 메모리 정보 등을 확인할 수 있어 애플리케이션의 성능 및 리소스 관리에 유용합니다.
console.log('플랫폼:', os.platform()); // 'win32', 'linux', 'darwin' 등
console.log('CPU 아키텍처:', os.arch()); // 'x64' 등
console.log('CPU 정보:', os.cpus()); // CPU 코어 정보
console.log('메모리(총량):', os.totalmem()); // 총 메모리 (바이트 단위)
console.log('메모리(사용 가능):', os.freemem()); // 사용 가능한 메모리
console.log('네트워크 인터페이스:', os.networkInterfaces()); // 네트워크 정보
console.log('호스트 이름:', os.hostname()); // 호스트 이름
console.log('시스템 업타임:', os.uptime(), '초'); // 시스템 가동 시간
URL 문자열을 쉽게 파싱하거나 조작할 수 있게 해줍니다.
new URL() 생성자를 사용하여 URL을 분석하고 구성 요소를 쉽게 다룰 수 있습니다.
const { URL } = require('url');
const myURL = new URL('https://example.com:8000/path?name=John#fragment');
console.log('호스트:', myURL.host); // 'example.com:8000'
console.log('경로명:', myURL.pathname); // '/path'
console.log('쿼리:', myURL.searchParams.get('name')); // 'John'
console.log('프래그먼트:', myURL.hash); // '#fragment'
URL의 쿼리 문자열을 쉽게 처리할 수 있도록 도와주는 모듈입니다.
GET 요청의 쿼리 파라미터를 처리할 때 유용합니다.
const querystring = require('querystring');
const query = 'name=John&age=30';
const parsed = querystring.parse(query);
console.log(parsed); // { name: 'John', age: '30' }
console.log(querystring.stringify(parsed)); // 'name=John&age=30'