Node.js는 JavaScript를 서버 사이드에서도 실행할 수 있게 해주는 런타임 환경으로, 현대 웹 개발에서 필수적인 도구입니다. 이번 포스트에서는 Node.js의 기초부터 설치, 사용 방법, 모듈 시스템 이해, 그리고 라이브러리 활용까지 상세히 알아보겠습니다.
Node.js는 Chrome V8 JavaScript 엔진으로 빌드된 JavaScript 런타임 환경입니다. 즉, 브라우저 밖에서도 JavaScript 코드를 실행할 수 있게 해줍니다.
비동기 이벤트 주도 방식으로 확장성 있는 네트워크 애플리케이션을 개발할 수 있습니다.
단일 스레드로 동작하지만, 비동기 I/O를 활용하여 높은 처리량을 보장합니다.
Node.js 공식 웹사이트로 이동합니다: https://nodejs.org/ko/
LTS(Long Term Support) 버전을 다운로드합니다.
안정성과 장기 지원을 위해 LTS 버전 사용을 권장합니다.
다운로드한 설치 파일을 실행하고 안내에 따라 설치를 완료합니다.
터미널이나 명령 프롬프트에서 다음 명령어로 설치 여부를 확인합니다.
node -v
설치된 Node.js의 버전이 출력되면 정상적으로 설치된 것입니다.
v18.17.1
또한, NPM이 함께 설치되었는지 확인합니다.
npm -v
NPM 버전이 출력됩니다.
9.6.7
Node.js로 가장 간단한 HTTP 서버를 만들어보겠습니다.
// server.js
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, Node.js!');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
실행하기
터미널에서 다음 명령어로 서버를 실행합니다.
node server.js
출력
Server running at http://127.0.0.1:3000/
브라우저에서 http://127.0.0.1:3000/에 접속하면 "Hello, Node.js!" 메시지를 볼 수 있습니다.
Node.js는 인터랙티브한 REPL 환경을 제공합니다.
node
JavaScript 코드를 바로 입력하고 실행 결과를 확인할 수 있습니다.
> console.log('Hello, REPL!');
Hello, REPL!
undefined
Ctrl + C 두 번 눌러 REPL을 종료합니다.
Node.js는 CommonJS 모듈 시스템을 사용합니다.
모듈은 파일 단위로 구성됩니다.
require() 함수를 사용하여 모듈을 가져옵니다.
module.exports 또는 exports 객체를 사용하여 모듈을 내보냅니다.
모듈 생성
// math.js
function add(a, b) {
return a + b;
}
module.exports = {
add,
};
모듈 사용
// app.js
const math = require('./math');
const result = math.add(2, 3);
console.log(result); // 출력: 5
Node.js 12버전 이상부터는 ES6 모듈을 지원합니다. 하지만 기본적으로는 CommonJS를 사용하므로, ES6 모듈을 사용하려면 파일 확장자를 .mjs로 하거나 package.json에 "type": "module"을 설정해야 합니다.
모듈 생성
// math.mjs
export function add(a, b) {
return a + b;
}
모듈 사용
// app.mjs
import { add } from './math.mjs';
const result = add(2, 3);
console.log(result); // 출력: 5
실행 방법
터미널에서 다음과 같이 실행합니다.
node app.mjs
NPM은 Node.js의 기본 패키지 관리자입니다.
전 세계 개발자들이 공유하는 수많은 패키지를 이용할 수 있습니다.
패키지를 설치하고 관리할 수 있습니다.
프로젝트 초기화
새로운 Node.js 프로젝트를 생성하려면 먼저 package.json 파일을 만들어야 합니다.
npm init -y
-y 옵션은 기본값으로 초기화합니다.
패키지 설치
예를 들어, 인기 있는 웹 프레임워크인 Express를 설치해보겠습니다.
npm install express
package.json의 dependencies에 "express": "^4.18.2"와 같이 추가됩니다.
node_modules 디렉토리에 패키지가 설치됩니다.
서버 생성
// index.js
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
실행하기
node index.js
출력
Example app listening at http://localhost:3000
브라우저에서 http://localhost:3000에 접속하면 "Hello, Express!" 메시지를 볼 수 있습니다.
5.3 기타 라이브러리 활용
npm install axios
const axios = require('axios');
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
npm install mongoose
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String,
email: String,
});
const User = mongoose.model('User', UserSchema);
const newUser = new User({ name: 'Alice', email: 'alice@example.com' });
newUser.save()
.then(() => console.log('User saved'))
.catch(err => console.error(err));
Node.js는 다양한 내장 모듈을 제공합니다. 추가적인 패키지 설치 없이 바로 사용할 수 있습니다.
파일을 읽고 쓰는 작업을 처리합니다.
const fs = require('fs');
// 비동기적으로 파일 읽기
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
// 동기적으로 파일 쓰기
fs.writeFileSync('example.txt', 'Hello, Node.js!');
파일 경로 작업을 쉽게 처리할 수 있습니다.
const path = require('path');
const fullPath = '/users/nodejs/app.js';
console.log(path.dirname(fullPath)); // 출력: '/users/nodejs'
console.log(path.basename(fullPath)); // 출력: 'app.js'
console.log(path.extname(fullPath)); // 출력: '.js'
간단한 HTTP 서버나 클라이언트를 만들 때 사용합니다.
const http = require('http');
http.get('http://example.com', (res) => {
console.log(`응답 상태 코드: ${res.statusCode}`);
});
전역 설치 예시
npm install -g nodemon
특정 버전의 패키지를 설치하거나 업데이트할 수 있습니다.
특정 버전 설치
npm install express@4.16.0
패키지 업데이트
npm update express
이번 포스트에서는 Node.js의 기초부터 시작하여 설치, 사용 방법, 모듈 시스템 이해, 그리고 라이브러리 활용까지 상세히 알아보았습니다. Node.js는 프론트엔드 개발자에게도 중요한 도구이며, 이를 잘 이해하고 활용하면 더욱 효율적이고 확장성 있는 애플리케이션을 개발할 수 있습니다.