Node.js 기초 · 내장 모듈 · npm과 패키지 · Express 기초
Chrome V8 엔진 위에서 동작하는 서버 사이드 JavaScript 런타임 Node.js의 기초 — REPL, 모듈 시스템(CommonJS/ESM), 파일 실행, process 객체를 익힙니다.
이 강의에서 배우는 것
- 1Node.js와 브라우저 JavaScript의 환경 차이를 안다
- 2REPL에서 즉시 코드를 실행한다
- 3CommonJS(require/exports)와 ESM(import/export)을 구분한다
- 4process.argv로 실행 인수를 처리한다
- 5fs로 파일을 동기·비동기로 읽고 쓴다
- 6path로 OS에 안전하게 경로를 조합한다
- 7os로 시스템 정보를 조회한다
- 8EventEmitter로 이벤트 구독/발행 패턴을 구현한다
- 9package.json의 주요 필드를 안다
- 10npm install / uninstall / list / scripts를 사용한다
- 11dependencies와 devDependencies를 구분한다
- 12nodemon으로 개발 서버를 자동 재시작한다
- 13.gitignore에서 node_modules와 .env를 제외한다
- 14express()로 앱을 생성하고 listen으로 포트를 연다
- 15GET/POST/PUT/DELETE 라우트를 등록한다
- 16req.params/query/body, res.send/json을 사용한다
- 17미들웨어 패턴(next 호출)을 이해한다
- 18express.static으로 정적 파일을 제공한다
Node.js 기초
1. Node.js란
Chrome V8 엔진 위에서 동작하는 서버 사이드 JavaScript 런타임. 웹 브라우저 없이도 컴퓨터에서 직접 JavaScript 코드를 실행합니다.
브라우저 환경: JavaScript → V8 엔진 → DOM/BOM API
Node.js 환경: JavaScript → V8 엔진 → Node.js API (fs, http, os …)2. 설치 확인
node --version # v18 이상 권장
npm --version설치가 안 되어 있다면 https://nodejs.org 에서 LTS 버전 설치.
3. REPL
터미널에 node를 입력하면 대화형 환경이 열립니다.
$ node
> 1 + 2
3
> 'Hello' + ' World'
'Hello World'
> Math.max(3, 7, 1)
7
> .exit4. 모듈 시스템
CommonJS (기본)
// 내보내기
module.exports = { add, subtract };
// 가져오기
const { add } = require('./math');
const fs = require('fs'); // 내장 모듈
const dayjs = require('dayjs'); // npm 패키지ESM (.mjs 또는 "type":"module")
// 내보내기
export function add(a, b) { return a + b; }
// 가져오기
import { add } from './math.js';
import fs from 'fs';이 강의에서는 CommonJS를 기본으로 사용합니다.
5. 파일 실행
node app.js # 기본 실행
node app.js 홍길동 # 인수 전달
node app.js 10 + 20 # 여러 인수6. process 객체
process.argv // 실행 인수 배열
process.env // 환경 변수
process.cwd() // 현재 작업 디렉토리
process.exit(0) // 프로세스 종료
process.platform // 'win32', 'darwin', 'linux'process.argv 예시
node app.js 홍길동console.log(process.argv);
// ['node경로', 'app.js경로', '홍길동']
const name = process.argv[2]; // '홍길동' (인수는 index 2부터)내장 모듈
Node.js가 기본 제공하는 핵심 모듈들 — fs(파일 시스템), path(경로 처리), os(운영체제 정보), events(이벤트 패턴)를 익힙니다.
1. fs 모듈
동기 방식
const fs = require('fs');
const content = fs.readFileSync('data.txt', 'utf-8');
fs.writeFileSync('output.txt', '저장할 내용', 'utf-8');
const exists = fs.existsSync('data.txt');
const files = fs.readdirSync('./');비동기 (콜백 / Promise)
// 콜백
fs.readFile('data.txt', 'utf-8', (err, data) => {
if (err) throw err;
console.log(data);
});
// Promise
const fs = require('fs/promises');
const data = await fs.readFile('data.txt', 'utf-8');2. path 모듈
OS마다 다른 경로 구분자(/, \)를 알아서 처리합니다.
const path = require('path');
path.join('/users', 'john', 'file.txt') // '/users/john/file.txt'
path.resolve('data', 'output.txt') // 절대 경로
path.dirname('/users/john/file.txt') // '/users/john'
path.basename('/users/john/file.txt') // 'file.txt'
path.extname('readme.md') // '.md'
// __dirname: 현재 파일이 있는 디렉토리의 절대 경로
const fullPath = path.join(__dirname, 'data', 'input.txt');3. os 모듈
const os = require('os');
os.platform() // 'win32', 'darwin', 'linux'
os.homedir() // 홈 디렉토리
os.hostname() // 컴퓨터 이름
os.cpus() // CPU 정보 배열
os.totalmem() // 전체 메모리 (bytes)
os.freemem() // 여유 메모리4. events 모듈 (EventEmitter)
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('data', (message) => {
console.log('데이터 수신:', message);
});
emitter.emit('data', '안녕하세요!');
// 한 번만 실행
emitter.once('connect', () => {
console.log('최초 연결!');
});npm과 패키지
package.json 구조와 npm 명령어, dependencies와 devDependencies의 차이, npx, nodemon, 그리고 실용 라이브러리 dayjs를 익힙니다.
1. package.json 구조
{
"name": "my-project",
"version": "1.0.0",
"description": "내 첫 Node.js 프로젝트",
"main": "index.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"test": "node test.js"
},
"dependencies": {
"express": "^4.18.2",
"dayjs": "^1.11.10"
},
"devDependencies": {
"nodemon": "^3.0.1"
}
}2. npm 기본 명령어
# 초기화
npm init # 질문에 답하며 생성
npm init -y # 기본값 자동 생성
# 설치
npm install express # 프로덕션 의존성
npm install --save-dev nodemon # 개발 의존성
npm install -g typescript # 전역 설치
# 목록
npm list
npm list --depth=0
# 제거
npm uninstall express
# 스크립트 실행
npm run dev
npm start # start는 run 생략 가능3. dependencies vs devDependencies
| 구분 | 설명 | 예시 |
|---|---|---|
| dependencies | 실제 실행에 필요 | express, dayjs |
| devDependencies | 개발 중에만 필요 | nodemon, eslint |
4. npx
npx create-react-app my-app # 설치 없이 바로 실행
npx cowsay "Hello, Node!" # 일회성 실행5. nodemon
npm install --save-dev nodemon{
"scripts": {
"dev": "nodemon server.js"
}
}npm run dev6. dayjs — 날짜/시간
npm install dayjsconst dayjs = require('dayjs');
dayjs() // 현재 시각
dayjs('2025-01-15') // 특정 날짜
dayjs().format('YYYY-MM-DD') // '2025-01-15'
dayjs().format('YYYY년 MM월 DD일') // '2025년 01월 15일'
dayjs().add(7, 'day') // 7일 후
dayjs().subtract(1, 'month') // 1달 전
dayjs().diff(dayjs('2000-01-01'), 'year') // 나이 계산7. .gitignore
# .gitignore
node_modules/
.env
*.lognode_modules는 용량이 크고 npm install로 언제든 복원 가능 — git에 올리지 않습니다.
Express 기초
Node.js의 가장 인기 있는 웹 프레임워크 Express로 HTTP 서버 띄우기, 라우팅, req/res 객체, 미들웨어, 정적 파일 제공까지 한 번에 다룹니다.
1. Express란
npm install expressconst express = require('express');
const app = express();
app.listen(3000, () => {
console.log('서버: http://localhost:3000');
});2. 라우팅
app.get('/', (req, res) => {
res.send('홈페이지입니다.');
});
app.post('/users', (req, res) => {
res.send('유저 생성');
});
app.put('/users/:id', (req, res) => {
res.send(`유저 ${req.params.id} 수정`);
});
app.delete('/users/:id', (req, res) => {
res.send(`유저 ${req.params.id} 삭제`);
});3. req / res
req (Request)
req.params // URL 파라미터: /users/:id → req.params.id
req.query // 쿼리스트링: /search?q=hello → req.query.q
req.body // 바디 (express.json() 필요)
req.headers // 헤더
req.method // 'GET', 'POST'
req.url // 요청 URLres (Response)
res.send('텍스트 응답');
res.json({ key: 'value' });
res.sendFile('/path/to/file.html');
res.redirect('/other-page');
res.status(404).send('Not Found');
res.render('index'); // EJS 등 템플릿4. 미들웨어
요청과 응답 사이에서 실행되는 함수입니다.
// 모든 요청에 적용
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // 다음 미들웨어로 넘김
});
// JSON 바디 파서
app.use(express.json());
// URL 인코딩 (폼 데이터)
app.use(express.urlencoded({ extended: true }));5. 정적 파일 제공
app.use(express.static('public'));
// http://localhost:3000/index.html → public/index.html
// http://localhost:3000/css/style.css → public/css/style.css6. 포트 설정
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`서버: http://localhost:${PORT}`);
});🧪 직접 돌려 본 결과와 오류
이 강의 내용을 코드로 만들어 2026-11-27 에 이 PC(Windows 11)에서 실제로 실행했습니다 — 브라우저는 크롬(창 없이 여는 헤드리스), 서버 · 스크립트는 Node.js v24.13.0. 아래 글자와 화면은 받은 그대로이고, 길게 반복되는 줄과 Node 내부 줄만 「… 줄임」으로 줄였습니다.
Express 서버를 띄우고 두 주소에 요청
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('안녕하세요, Express!');
});
app.get('/api/users/:id', (req, res) => {
res.json({ id: Number(req.params.id), name: '김지훈' });
});
app.listen(3123, () => {
console.log('서버: http://localhost:3123');
});$ node server.js
서버: http://localhost:3123
$ curl -s -i http://localhost:3123/
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 25
ETag: W/"19-cQvq8KXzMlHDGueoN15Euf7wyAA"
Date: Fri, 27 Nov 2026 01:35:17 GMT
Connection: keep-alive
Keep-Alive: timeout=5
안녕하세요, Express!
$ curl -s -i http://localhost:3123/api/users/7
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 27
ETag: W/"1b-GaLJJzhdLrogBI8ywLoah4eiSuY"
Date: Fri, 27 Nov 2026 01:35:17 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"id":7,"name":"김지훈"}
$ curl -s -i http://localhost:3123/no-such-page
HTTP/1.1 404 Not Found
X-Powered-By: Express
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 151
Date: Fri, 27 Nov 2026 01:35:17 GMT
Connection: keep-alive
Keep-Alive: timeout=5
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /no-such-page</pre>
</body>
</html>보이는 것: express 로 서버를 띄우고 다른 터미널에서 curl 로 요청한 결과입니다. res.send 는 text/html, res.json 은 application/json 으로 응답하고, 정하지 않은 주소에는 Express 가 404 'Cannot GET …'을 돌려줍니다.
같은 포트로 서버를 하나 더 띄우면 — Express 5 의 listen 콜백
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('안녕하세요, Express!');
});
app.get('/api/users/:id', (req, res) => {
res.json({ id: Number(req.params.id), name: '김지훈' });
});
app.listen(3123, () => {
console.log('서버: http://localhost:3123');
});(터미널 1) $ node server.js; echo "(종료 코드 $?)"
서버: http://localhost:3123
(터미널 2) $ node server.js; echo "(종료 코드 $?)"
서버: http://localhost:3123
(종료 코드 0)왜: Express 5 의 app.listen 은 포트가 이미 쓰이고 있으면(EADDRINUSE) 그 오류를 콜백의 첫 인수로 넘깁니다. 본문처럼 인수 없이 성공 문구만 찍으면, 터미널 2 는 서버를 못 띄웠는데도 '서버: …'를 찍고 종료 코드 0 으로 끝납니다.
고치는 법: 콜백에서 err 를 먼저 확인합니다(고친 뒤 'EADDRINUSE' · 종료 코드 1). 그 포트를 쓰는 다른 프로그램을 끄거나 다른 포트를 씁니다.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('안녕하세요, Express!');
});
app.get('/api/users/:id', (req, res) => {
res.json({ id: Number(req.params.id), name: '김지훈' });
});
app.listen(3123, (err) => {
if (err) {
console.error('서버를 띄우지 못함:', err.code);
process.exit(1);
}
console.log('서버: http://localhost:3123');
});(터미널 1) $ node server.js; echo "(종료 코드 $?)"
서버: http://localhost:3123
(터미널 2) $ node server.js; echo "(종료 코드 $?)"
서버를 띄우지 못함: EADDRINUSE
(종료 코드 1)package.json 이 "type": "commonjs" 인데 import 를 쓰면
{
"name": "my-app",
"version": "1.0.0",
"type": "commonjs"
}import path from 'path';
console.log(path.basename('/users/john/file.txt'));$ node app.js
(node:21992) Warning: Failed to load the ES module: F:\pylec\web\cases\node-01-basics\3\app.js. Make sure to set "type": "module" in the nearest package.json file or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
F:\pylec\web\cases\node-01-basics\3\app.js:1
import path from 'path';
^^^^^^
SyntaxError: Cannot use import statement outside a module
… (내부 8줄 줄임)
at node:internal/main/run_main_module:33:47
Node.js v24.13.0왜: 가장 가까운 package.json 이 "type": "commonjs" 라 .js 를 CommonJS 로 읽어 import 문에서 SyntaxError 가 났습니다. Node 가 경고로 고치는 법도 알려 줍니다. 이 PC 에서 npm init -y 로 만든 package.json 에도 "type": "commonjs" 가 들어 있었습니다.
고치는 법: package.json 의 type 을 "module" 로 바꾸거나 파일 확장자를 .mjs 로 합니다.
{
"name": "my-app",
"version": "1.0.0",
"type": "module"
}import path from 'path';
console.log(path.basename('/users/john/file.txt'));$ node app.js
file.txt"type": "module" 프로젝트에서 require 를 쓰면
{
"name": "my-app",
"version": "1.0.0",
"type": "module"
}const path = require('path');
console.log(path.basename('/users/john/file.txt'));$ node app.js
file:///F:/pylec/web/cases/node-01-basics/4/app.js:1
const path = require('path');
^
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and 'F:\pylec\web\cases\node-01-basics\4\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///F:/pylec/web/cases/node-01-basics/4/app.js:1:14
at ModuleJob.run (node:internal/modules/esm/module_job:413:25)
at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:660:26)
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:101:5)
Node.js v24.13.0왜: "type": "module" 이면 .js 가 ES 모듈이라 require 가 없습니다. 오류 문구가 import 를 쓰거나 .cjs 로 바꾸라고 알려 줍니다.
고치는 법: import path from 'path' 로 바꿉니다.
{
"name": "my-app",
"version": "1.0.0",
"type": "module"
}import path from 'path';
console.log(path.basename('/users/john/file.txt'));$ node app.js
file.txt댓글 0
아직 댓글이 없습니다. 첫 댓글을 남겨 주세요.
댓글은 회원만 쓸 수 있습니다.
광고·욕설·비방·개인정보·불법 내용이 담긴 댓글은 숨기거나 지웁니다. 광고·홍보 글이나 혐오·비방 글을 올린 회원은 강제 탈퇴되고 쓴 글이 모두 지워집니다. 댓글은 닉네임과 함께 공개됩니다. 개인정보처리방침