Node.js ๋ฐฑ์๋ ๋ฉด์ ์ง๋ฌธ: ์๋ฒฝ ๊ฐ์ด๋ 2026
Node.js ๋ฐฑ์๋ ๋ฉด์ ์์ ๊ฐ์ฅ ์์ฃผ ๋์ค๋ 25๊ฐ์ง ์ง๋ฌธ. Event loop, async/await, streams, ํด๋ฌ์คํฐ๋ง, ์ฑ๋ฅ์ ์์ธํ ๋ต๋ณ๊ณผ ํจ๊ป ์ค๋ช ํฉ๋๋ค.

Node.js ๋ฐฑ์๋ ๋ฉด์ ์์๋ ๋ฐํ์ ๋ด๋ถ ๋ฉ์ปค๋์ฆ์ ์ดํด, ๋น๋๊ธฐ ํจํด์ ์๋ฌ, ๊ณ ์ฑ๋ฅ ์ ํ๋ฆฌ์ผ์ด์ ์ค๊ณ ๋ฅ๋ ฅ์ด ํ๊ฐ๋ฉ๋๋ค. ์ด ๊ฐ์ด๋๋ ๊ธฐ์ด๋ถํฐ ํ๋ก๋์ ํ๊ฒฝ์ ๊ณ ๊ธ ๊ฐ๋ ๊น์ง ๊ฐ์ฅ ์์ฃผ ์ถ์ ๋๋ ์ง๋ฌธ์ ๋ค๋ฃน๋๋ค.
์ฑ์ฉ ๋ด๋น์๋ ์ด๋ก ๊ณผ ์ค์ ์์ ๋ฅผ ๊ฒฐํฉํ ๋ต๋ณ์ ๋์ด ํ๊ฐํฉ๋๋ค. ๊ฐ ์ง๋ฌธ์ ๋ํด ์ฝ๋๋ ๊ตฌ์ฒด์ ์ธ ์ฌ์ฉ ์ฌ๋ก๋ก ์ค๋ช ํ๋ฉด ์ค๋ฌด ๊ฒฝํ์ด ์ ๋ฌ๋ฉ๋๋ค.
Node.js ๊ธฐ์ด
์ง๋ฌธ 1: Event Loop๋ ๋ฌด์์ด๋ฉฐ ์ด๋ป๊ฒ ๋์ํ๋๊ฐ?
Event Loop๋ Node.js๊ฐ ์ฑ๊ธ ์ค๋ ๋๋ก ๋์ํ๋ฉด์๋ ๋น๋๊ธฐ ์์ ์ ๋ ผ๋ธ๋กํน ๋ฐฉ์์ผ๋ก ์ฒ๋ฆฌํ ์ ์๊ฒ ํ๋ ํต์ฌ ๋ฉ์ปค๋์ฆ์ ๋๋ค. JavaScript ์ฝ๋, ์ฝ๋ฐฑ, ์ด๋ฒคํธ์ ์คํ์ ์กฐ์จํฉ๋๋ค.
// Demonstration of Event Loop execution order
console.log('1. Script start (synchronous)');
// setTimeout goes to the Timer Queue
setTimeout(() => {
console.log('5. setTimeout callback (Timer Queue)');
}, 0);
// setImmediate goes to the Check Queue
setImmediate(() => {
console.log('6. setImmediate callback (Check Queue)');
});
// Promise goes to the Microtask Queue (priority)
Promise.resolve().then(() => {
console.log('3. Promise.then (Microtask Queue)');
});
// process.nextTick has the highest priority
process.nextTick(() => {
console.log('2. process.nextTick (nextTick Queue)');
});
console.log('4. Script end (synchronous)');
// Output order: 1, 4, 2, 3, 5, 6Event Loop๋ ํ๋ฅผ ์ฒ๋ฆฌํ ๋ ์ ํํ ์์๋ฅผ ๋ฐ๋ฆ ๋๋ค. ๋จผ์ ๋๊ธฐ ์ฝ๋, ๊ทธ ๋ค์ nextTick, ๋ง์ดํฌ๋กํ์คํฌ(Promise), ํ์ด๋จธ, I/O ์ฝ๋ฐฑ, setImmediate, ๋ง์ง๋ง์ผ๋ก ๋ซ๊ธฐ ์ฝ๋ฐฑ ์์ ๋๋ค.
์ง๋ฌธ 2: process.nextTick()๊ณผ setImmediate()์ ์ฐจ์ด์ ์?
์ด ์ง๋ฌธ์ Event Loop์์์ ์คํ ์ฐ์ ์์์ ๋ํ ์ธ๋ฐํ ์ดํด๋ฅผ ํ๊ฐํฉ๋๋ค.
// Behavior comparison
// process.nextTick executes BEFORE the next Event Loop phase
process.nextTick(() => {
console.log('nextTick 1');
process.nextTick(() => {
console.log('nextTick 2 (nested)');
});
});
// setImmediate executes in the Check phase of the Event Loop
setImmediate(() => {
console.log('setImmediate 1');
setImmediate(() => {
console.log('setImmediate 2 (nested)');
});
});
// Output: nextTick 1, nextTick 2, setImmediate 1, setImmediate 2process.nextTick()์ ํ์ฌ ์์
์งํ, Event Loop๊ฐ ๊ณ์๋๊ธฐ ์ ์ ์ฒ๋ฆฌ๋ฉ๋๋ค. ๊ณผ๋ํ ์ฌ์ฉ์ Event Loop๋ฅผ ์ฐจ๋จํ ์ ์์ต๋๋ค. setImmediate()๋ ๋ ์์ธก ๊ฐ๋ฅํ๋ฉฐ ์คํ ์ง์ฐ์ ๊ถ์ฅ๋ฉ๋๋ค.
process.nextTick()์ ์ฌ๊ท ํธ์ถ์ Event Loop๋ฅผ ๊ณ ๊ฐ์ํค๊ณ I/O ์ฒ๋ฆฌ๋ฅผ ๋ฐฉํดํ ์ ์์ต๋๋ค. ์ค์ํ์ง ์์ ์์ ์๋ setImmediate() ์ฌ์ฉ์ด ๊ถ์ฅ๋ฉ๋๋ค.
์ง๋ฌธ 3: Node.js๋ ๋น๋๊ธฐ ์ฝ๋์์ ์ค๋ฅ๋ฅผ ์ด๋ป๊ฒ ์ฒ๋ฆฌํ๋๊ฐ?
๋น๋๊ธฐ ์ค๋ฅ ์ฒ๋ฆฌ๋ ๋๊ธฐ ์ฝ๋์ ๊ทผ๋ณธ์ ์ผ๋ก ๋ค๋ฆ ๋๋ค. ์ ์ ํ ์ฒ๋ฆฌ ์์ด๋ ์ค๋ฅ๊ฐ ์ ํ๋ฆฌ์ผ์ด์ ์ ํฌ๋์์ํฌ ์ ์์ต๋๋ค.
// Asynchronous error handling patterns
// Pattern 1: Callbacks with error-first convention
function readFileCallback(path, callback) {
const fs = require('fs');
fs.readFile(path, 'utf8', (err, data) => {
if (err) {
// Error is ALWAYS the first argument
return callback(err, null);
}
callback(null, data);
});
}
// Pattern 2: Promises with catch
async function readFilePromise(path) {
const fs = require('fs').promises;
try {
const data = await fs.readFile(path, 'utf8');
return data;
} catch (err) {
// Centralized error handling
console.error(`File read error: ${err.message}`);
throw err; // Re-throw for propagation
}
}
// Pattern 3: Global handling of unhandled rejections
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled rejection:', reason);
// In production: log and graceful shutdown
});
// Pattern 4: Handling uncaught exceptions
process.on('uncaughtException', (err) => {
console.error('Uncaught exception:', err);
// CRITICAL: always terminate the process after
process.exit(1);
});ํ๋ก๋์
ํ๊ฒฝ์์ ๋ชจ๋ Promise๋ .catch()๋ฅผ ๊ฐ๊ฑฐ๋ try/catch ๋ธ๋ก ์์ ์์ด์ผ ํฉ๋๋ค. ๊ธ๋ก๋ฒ ํธ๋ค๋ฌ๋ ์์ ๋ง ์ญํ ์ ํ๋ฉฐ ์ฃผ์ ์๋ฃจ์
์ด ์๋๋๋ค.
๋น๋๊ธฐ ํ๋ก๊ทธ๋๋ฐ๊ณผ ๋์์ฑ
์ง๋ฌธ 4: Node.js์์ ๋ณ๋ ฌ ์ฒ๋ฆฌ์ ๋์ ์ฒ๋ฆฌ์ ์ฐจ์ด๋ฅผ ์ค๋ช ํ๋ผ
Node.js๋ ๊ธฐ๋ณธ์ ์ผ๋ก ๋์์ ์ด์ง๋ง ๋ณ๋ ฌ์ ์ด์ง๋ ์์ต๋๋ค. ์ด ๊ตฌ๋ถ์ ์ฑ๋ฅ ์ดํด์ ํ์์ ์ ๋๋ค.
// CONCURRENCY: multiple tasks progress by alternating (single-thread)
async function concurrentTasks() {
console.time('concurrent');
// These calls are concurrent, not parallel
const results = await Promise.all([
fetch('https://api.example.com/users'), // Non-blocking I/O
fetch('https://api.example.com/products'), // Non-blocking I/O
fetch('https://api.example.com/orders'), // Non-blocking I/O
]);
console.timeEnd('concurrent'); // ~time of the longest request
return results;
}
// PARALLELISM: with Worker Threads for CPU-bound tasks
const { Worker, isMainThread, parentPort } = require('worker_threads');
if (isMainThread) {
// Main thread delegates CPU-intensive work
async function parallelComputation() {
console.time('parallel');
const workers = [
createWorker({ start: 0, end: 1000000 }),
createWorker({ start: 1000000, end: 2000000 }),
createWorker({ start: 2000000, end: 3000000 }),
];
const results = await Promise.all(workers);
console.timeEnd('parallel');
return results.reduce((a, b) => a + b, 0);
}
function createWorker(data) {
return new Promise((resolve, reject) => {
const worker = new Worker(__filename, { workerData: data });
worker.on('message', resolve);
worker.on('error', reject);
});
}
} else {
// Code executed in the Worker Thread
const { workerData } = require('worker_threads');
let sum = 0;
for (let i = workerData.start; i < workerData.end; i++) {
sum += Math.sqrt(i); // CPU-intensive calculation
}
parentPort.postMessage(sum);
}I/O ๋ฐ์ด๋ ์์ (๋คํธ์ํฌ, ํ์ผ)์๋ ๋ค์ดํฐ๋ธ ๋์์ฑ์ผ๋ก ์ถฉ๋ถํฉ๋๋ค. CPU ๋ฐ์ด๋ ์์ (๋ฌด๊ฑฐ์ด ๊ณ์ฐ, ์ํธํ)์๋ Worker Threads๊ฐ ์ง์ ํ ๋ณ๋ ฌ ์ฒ๋ฆฌ๋ฅผ ๊ฐ๋ฅํ๊ฒ ํฉ๋๋ค.
์ง๋ฌธ 5: Cluster ๋ชจ๋์ ์ด๋ป๊ฒ ๋์ํ๋๊ฐ?
Cluster ๋ชจ๋์ ๊ฐ์ ํฌํธ๋ฅผ ๊ณต์ ํ๋ ์ฌ๋ฌ Node.js ํ๋ก์ธ์ค๋ฅผ ์์ฑํ์ฌ ์ฌ์ฉ ๊ฐ๋ฅํ ๋ชจ๋ CPU ์ฝ์ด๋ฅผ ํ์ฉํฉ๋๋ค.
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isPrimary) {
console.log(`Primary ${process.pid} is running`);
console.log(`Forking ${numCPUs} workers...`);
// Fork one worker per CPU core
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
// Handle crashing workers
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died (${signal || code})`);
console.log('Starting a new worker...');
cluster.fork(); // Automatic restart
});
// Inter-process communication
cluster.on('message', (worker, message) => {
console.log(`Message from worker ${worker.id}:`, message);
});
} else {
// Workers share the TCP port
http.createServer((req, res) => {
res.writeHead(200);
res.end(`Handled by worker ${process.pid}\n`);
// Send stats to primary
process.send({ type: 'request', pid: process.pid });
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}๋ก๋ ๋ฐธ๋ฐ์ฑ์ ์ด์์ฒด์ ๊ฐ ์๋์ผ๋ก ์ฒ๋ฆฌํฉ๋๋ค(Linux/macOS์์ ๋ผ์ด๋ ๋ก๋น). ํ๋ก๋์ ์์๋ PM2๊ฐ ๋ด์ฅ ํด๋ฌ์คํฐ ๋ชจ๋๋ก ์ด ๊ด๋ฆฌ๋ฅผ ๊ฐ์ํํฉ๋๋ค.
Node.js / NestJS ๋ฉด์ ์ค๋น๊ฐ ๋์ จ๋์?
์ธํฐ๋ํฐ๋ธ ์๋ฎฌ๋ ์ดํฐ, flashcards, ๊ธฐ์ ํ ์คํธ๋ก ์ฐ์ตํ์ธ์.
Streams์ Buffers
์ง๋ฌธ 6: ํด๋์ ๋ฉ์๋ ๋์ Streams๋ฅผ ์ฌ์ฉํด์ผ ํ๋ ๊ฒฝ์ฐ๋?
Streams๋ ๋ชจ๋ ๊ฒ์ ๋ฉ๋ชจ๋ฆฌ์ ๋ก๋ํ๋ ๋์ ์ฒญํฌ ๋จ์๋ก ๋ฐ์ดํฐ๋ฅผ ์ฒ๋ฆฌํฉ๋๋ค. ๋์ฉ๋ ํ์ผ๊ณผ ์คํธ๋ฆฌ๋ฐ ์๋๋ฆฌ์ค์ ํ์์ ์ ๋๋ค.
const fs = require('fs');
// โ BAD: loads entire file into memory
async function readEntireFile(path) {
const data = await fs.promises.readFile(path); // Blocks if file > RAM
return processData(data);
}
// โ
GOOD: chunk-based processing with Stream
function readWithStream(path) {
return new Promise((resolve, reject) => {
const chunks = [];
const readStream = fs.createReadStream(path, {
highWaterMark: 64 * 1024, // 64KB per chunk
});
readStream.on('data', (chunk) => {
// Progressive processing, constant memory
chunks.push(processChunk(chunk));
});
readStream.on('end', () => resolve(chunks));
readStream.on('error', reject);
});
}
// โ
BEST: pipeline for chaining transformations
const { pipeline } = require('stream/promises');
const zlib = require('zlib');
async function compressFile(input, output) {
await pipeline(
fs.createReadStream(input), // Source
zlib.createGzip(), // Transform
fs.createWriteStream(output) // Destination
);
// Automatic error handling and backpressure management
}๋ฐ์ดํฐ ํฌ๊ธฐ๊ฐ ์ MB๋ฅผ ์ด๊ณผํ ์ ์๋ ๊ฒฝ์ฐ, ๋๋ ์ค์๊ฐ ์ฒ๋ฆฌ(์ ๋ก๋, ๋ก๊ทธ, ๋คํธ์ํฌ ๋ฐ์ดํฐ)์ Streams ์ฌ์ฉ์ด ๊ถ์ฅ๋ฉ๋๋ค.
์ง๋ฌธ 7: ๋ฐฑํ๋ ์ ๊ฐ๋ ์ ์ค๋ช ํ๋ผ
๋ฐฑํ๋ ์ ๋ ๋ฐ์ดํฐ ์์ฐ์๊ฐ ์๋น์๋ณด๋ค ๋น ๋ฅผ ๋ ๋ฐ์ํฉ๋๋ค. ๊ด๋ฆฌํ์ง ์์ผ๋ฉด ๋ฉ๋ชจ๋ฆฌ๊ฐ ํญ๋ฐํฉ๋๋ค.
const fs = require('fs');
// โ Problem: no backpressure handling
function badCopy(src, dest) {
const readable = fs.createReadStream(src);
const writable = fs.createWriteStream(dest);
readable.on('data', (chunk) => {
// If write() returns false, the internal buffer is full
// But here reading continues anyway โ memory leak
writable.write(chunk);
});
}
// โ
Solution: respect the writable signal
function goodCopy(src, dest) {
const readable = fs.createReadStream(src);
const writable = fs.createWriteStream(dest);
readable.on('data', (chunk) => {
const canContinue = writable.write(chunk);
if (!canContinue) {
// Pause reading until buffer drains
readable.pause();
}
});
writable.on('drain', () => {
// Buffer drained, resume reading
readable.resume();
});
readable.on('end', () => writable.end());
}
// โ
BEST: pipe() handles everything automatically
function bestCopy(src, dest) {
const readable = fs.createReadStream(src);
const writable = fs.createWriteStream(dest);
// pipe() handles backpressure natively
readable.pipe(writable);
}pipe() ๋๋ pipeline() ๋ฉ์๋๊ฐ ๋ฐฑํ๋ ์
๋ฅผ ์๋์ผ๋ก ์ฒ๋ฆฌํฉ๋๋ค. ๋ณต์กํ ๊ฒฝ์ฐ์๋ pause/resume ๋ก์ง์ ์๋์ผ๋ก ๊ตฌํํฉ๋๋ค.
์ฑ๋ฅ๊ณผ ์ต์ ํ
์ง๋ฌธ 8: ๋ฉ๋ชจ๋ฆฌ ๋์๋ฅผ ์๋ณํ๊ณ ์์ ํ๋ ๋ฐฉ๋ฒ์?
๋ฉ๋ชจ๋ฆฌ ๋์๋ Node.js์์ ํํ ๋ฐ์ํฉ๋๋ค. ํ๋ก๋์ ์์ ๊ฐ์งํ๊ณ ์์ ํ๋ ๋ฐฉ๋ฒ์ ์๋ ๊ฒ์ด ํ์์ ์ ๋๋ค.
// โ Leak 1: closures that retain references
function createLeakyHandler() {
const hugeData = Buffer.alloc(100 * 1024 * 1024); // 100MB
return function handler(req, res) {
// hugeData remains in memory as long as handler exists
res.end('Hello');
};
}
// โ
Fix: limit the scope
function createSafeHandler() {
return function handler(req, res) {
// Data created and released on each request
const data = fetchData();
res.end(data);
};
}
// โ Leak 2: event listeners not cleaned up
class LeakyClass {
constructor() {
// Added on each instantiation, never removed
process.on('message', this.handleMessage);
}
handleMessage(msg) { /* ... */ }
}
// โ
Fix: explicit cleanup
class SafeClass {
constructor() {
this.boundHandler = this.handleMessage.bind(this);
process.on('message', this.boundHandler);
}
handleMessage(msg) { /* ... */ }
destroy() {
// Mandatory cleanup
process.removeListener('message', this.boundHandler);
}
}
// Diagnostics with native tools
function diagnoseMemory() {
const used = process.memoryUsage();
console.log({
heapUsed: `${Math.round(used.heapUsed / 1024 / 1024)}MB`,
heapTotal: `${Math.round(used.heapTotal / 1024 / 1024)}MB`,
external: `${Math.round(used.external / 1024 / 1024)}MB`,
rss: `${Math.round(used.rss / 1024 / 1024)}MB`,
});
}
// Enable manual garbage collector for testing
// node --expose-gc app.js
if (global.gc) {
global.gc();
diagnoseMemory();
}ํ๋ก๋์
์์๋ clinic.js, Chrome DevTools์ ํ ์ค๋
์ท, ๋๋ DataDog์ด๋ New Relic ๊ฐ์ APM ์๋ฃจ์
์ด ์ฌ์ฉ๋ฉ๋๋ค.
์ง๋ฌธ 9: Node.js API ์ฑ๋ฅ์ ์ต์ ํํ๋ ๋ฐฉ๋ฒ์?
์ด ์ง๋ฌธ์ ์ฌ๋ฌ ์์ค์ ์ต์ ํ ๊ธฐ๋ฒ์ ๋ํ ์ง์์ ํ๊ฐํฉ๋๋ค.
// 1. CACHING: reduce expensive calls
const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 300 }); // 5-minute TTL
async function getCachedUser(id) {
const cacheKey = `user:${id}`;
let user = cache.get(cacheKey);
if (!user) {
user = await db.users.findById(id);
cache.set(cacheKey, user);
}
return user;
}
// 2. CONNECTION POOLING: reuse DB connections
const { Pool } = require('pg');
const pool = new Pool({
max: 20, // Max simultaneous connections
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 2000,
});
// 3. COMPRESSION: reduce response size
const compression = require('compression');
app.use(compression({
filter: (req, res) => {
// Only compress if > 1KB
return compression.filter(req, res);
},
threshold: 1024,
}));
// 4. BATCHING: group operations
async function batchInsert(items) {
const BATCH_SIZE = 1000;
for (let i = 0; i < items.length; i += BATCH_SIZE) {
const batch = items.slice(i, i + BATCH_SIZE);
await db.items.insertMany(batch);
}
}
// 5. LAZY LOADING: load on demand
async function getUserWithPosts(userId, includePosts = false) {
const user = await db.users.findById(userId);
if (includePosts) {
user.posts = await db.posts.findByUserId(userId);
}
return user;
}์ต์ ํ๋ ํ๋กํ์ผ๋ง์ ๊ธฐ๋ฐํด์ผ ํฉ๋๋ค. ์ต์ ํ ์ ์ ์ธก์ ํ์ฌ ์ค์ ๋ณ๋ชฉ ์ง์ ์ ์๋ณํ๋ ๊ฒ์ด ์ค์ํฉ๋๋ค.
์ฑ๋ฅ ๋ฌธ์ ์ 80%๋ ์ฝ๋์ 20%์์ ๋ฐ์ํฉ๋๋ค. ํ๋กํ์ผ๋ง์ ํตํด ๋งน๋ชฉ์ ์ผ๋ก ์ต์ ํํ๊ธฐ ์ ์ ์ด๋ฌํ ์ค์ ์์ญ์ ์๋ณํ ์ ์์ต๋๋ค.
๋ณด์
์ง๋ฌธ 10: Node.js API๋ฅผ ์ผ๋ฐ์ ์ธ ๊ณต๊ฒฉ์ผ๋ก๋ถํฐ ๋ณดํธํ๋ ๋ฐฉ๋ฒ์?
๋ณด์์ ๋ฉด์ ์์ ๋ฐ๋ณต์ ์ผ๋ก ๋์ค๋ ์ฃผ์ ์ ๋๋ค. OWASP ์ทจ์ฝ์ ์ ๋ํ ์ง์์ ๋ณด์ฌ์ฃผ๋ ๊ฒ์ด ๊ธฐ๋๋ฉ๋๋ค.
const express = require('express');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const mongoSanitize = require('express-mongo-sanitize');
const xss = require('xss-clean');
const app = express();
// 1. SECURITY HEADERS with Helmet
app.use(helmet());
// 2. RATE LIMITING against brute-force attacks
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // 100 requests per IP
message: 'Too many requests, please try again later',
standardHeaders: true,
legacyHeaders: false,
});
app.use('/api/', limiter);
// 3. SANITIZATION against NoSQL injections
app.use(mongoSanitize());
// 4. XSS PROTECTION
app.use(xss());
// 5. STRICT INPUT VALIDATION
const { body, validationResult } = require('express-validator');
app.post('/api/users',
[
body('email').isEmail().normalizeEmail(),
body('password').isLength({ min: 8 }).escape(),
body('name').trim().escape(),
],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Continue processing
}
);
// 6. SQL INJECTION PROTECTION (with parameters)
async function safeQuery(userId) {
// โ
Parameterized query
const result = await pool.query(
'SELECT * FROM users WHERE id = $1',
[userId]
);
return result.rows;
}
// โ NEVER string concatenation
async function unsafeQuery(userId) {
// Vulnerable to SQL injection
const result = await pool.query(
`SELECT * FROM users WHERE id = ${userId}`
);
}ํ๋ก๋์
์์๋ ์ ํ์ ์ธ CORS, ํ์ HTTPS, ๋ณด์ ๋ก๊น
, ์ํฌ๋ฆฟ ๋กํ
์ด์
, ์ ๊ธฐ์ ์ธ ์์กด์ฑ ๊ฐ์ฌ(npm audit)๋ ์ถ๊ฐํด์ผ ํฉ๋๋ค.
์ํคํ ์ฒ์ ๋์์ธ ํจํด
์ง๋ฌธ 11: Node.js์์ Repository ํจํด์ ์ค๋ช ํ๋ผ
Repository ํจํด์ ๋ฐ์ดํฐ ์ ๊ทผ์ ์ถ์ํํ๊ณ ํ ์คํธ์ ์ ์ง๋ณด์๋ฅผ ์ฉ์ดํ๊ฒ ํฉ๋๋ค.
// Abstract interface (for TypeScript, or documentation)
class UserRepository {
async findById(id) { throw new Error('Not implemented'); }
async findByEmail(email) { throw new Error('Not implemented'); }
async create(userData) { throw new Error('Not implemented'); }
async update(id, userData) { throw new Error('Not implemented'); }
async delete(id) { throw new Error('Not implemented'); }
}
// Concrete implementation with Prisma
class PrismaUserRepository extends UserRepository {
constructor(prisma) {
super();
this.prisma = prisma;
}
async findById(id) {
return this.prisma.user.findUnique({ where: { id } });
}
async findByEmail(email) {
return this.prisma.user.findUnique({ where: { email } });
}
async create(userData) {
return this.prisma.user.create({ data: userData });
}
async update(id, userData) {
return this.prisma.user.update({
where: { id },
data: userData,
});
}
async delete(id) {
return this.prisma.user.delete({ where: { id } });
}
}
// Implementation for testing
class InMemoryUserRepository extends UserRepository {
constructor() {
super();
this.users = new Map();
this.idCounter = 1;
}
async findById(id) {
return this.users.get(id) || null;
}
async create(userData) {
const user = { id: this.idCounter++, ...userData };
this.users.set(user.id, user);
return user;
}
// ... other methods
}
// Service using the repository (dependency injection)
class UserService {
constructor(userRepository) {
this.userRepository = userRepository;
}
async getUser(id) {
const user = await this.userRepository.findById(id);
if (!user) throw new Error('User not found');
return user;
}
}์ด ํจํด์ ํตํด ๋น์ฆ๋์ค ๋ก์ง์ ์์ ํ์ง ์๊ณ ์์์ฑ ๊ตฌํ์ ๋ณ๊ฒฝํ ์ ์์ต๋๋ค.
์ง๋ฌธ 12: ์์ ํ ์์คํ ์ ๊ตฌํํ๋ ๋ฐฉ๋ฒ์?
ํ๋ ๋ฌด๊ฑฐ์ด ์์ ์ ์ง์ฐ์ํค๊ณ ์์ ์ ์ธ ์คํ์ ๋ณด์ฅํฉ๋๋ค.
const Queue = require('bull');
// Create queue with Redis as backend
const emailQueue = new Queue('email', {
redis: {
host: 'localhost',
port: 6379,
},
defaultJobOptions: {
attempts: 3, // Number of attempts
backoff: {
type: 'exponential',
delay: 2000, // Initial delay between attempts
},
removeOnComplete: 100, // Keep last 100 completed jobs
},
});
// Producer: add jobs to the queue
async function sendWelcomeEmail(userId, email) {
await emailQueue.add('welcome', {
userId,
email,
template: 'welcome',
}, {
priority: 1, // High priority
delay: 5000, // 5-second delay
});
}
// Consumer: process jobs
emailQueue.process('welcome', async (job) => {
const { userId, email, template } = job.data;
// Update progress
job.progress(10);
const html = await renderTemplate(template, { userId });
job.progress(50);
await sendEmail(email, 'Welcome!', html);
job.progress(100);
return { sent: true, email };
});
// Event handling
emailQueue.on('completed', (job, result) => {
console.log(`Job ${job.id} completed:`, result);
});
emailQueue.on('failed', (job, err) => {
console.error(`Job ${job.id} failed:`, err.message);
});
// Recurring jobs (cron)
emailQueue.add('newsletter', { type: 'weekly' }, {
repeat: {
cron: '0 9 * * MON', // Every Monday at 9am
},
});Bull + Redis๊ฐ ๊ฐ์ฅ ์ธ๊ธฐ ์๋ ์๋ฃจ์
์
๋๋ค. ๋ ๊ฐ๋จํ ์๊ตฌ์ฌํญ์๋ agenda๋ bee-queue๊ฐ ๊ฒฝ๋ ๋์์
๋๋ค.
๊ณ ๊ธ ์ง๋ฌธ
์ง๋ฌธ 13: ๋ค์ดํฐ๋ธ N-API ๋ชจ๋์ ์ด๋ป๊ฒ ๋์ํ๋๊ฐ?
N-API๋ฅผ ํตํด Node.js ๋ฒ์ ๊ฐ ์์ ์ ์ธ API๋ฅผ ๊ฐ์ง C/C++ ๋ค์ดํฐ๋ธ ๋ชจ๋์ ์์ฑํ ์ ์์ต๋๋ค.
// Native module for CPU-intensive calculations
#include <napi.h>
// Synchronous function exposed to JavaScript
Napi::Number Fibonacci(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
// Argument validation
if (info.Length() < 1 || !info[0].IsNumber()) {
Napi::TypeError::New(env, "Number expected")
.ThrowAsJavaScriptException();
return Napi::Number::New(env, 0);
}
int n = info[0].As<Napi::Number>().Int32Value();
// Iterative Fibonacci calculation
long long a = 0, b = 1;
for (int i = 0; i < n; i++) {
long long temp = a + b;
a = b;
b = temp;
}
return Napi::Number::New(env, static_cast<double>(a));
}
// Module initialization
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(
Napi::String::New(env, "fibonacci"),
Napi::Function::New(env, Fibonacci)
);
return exports;
}
NODE_API_MODULE(native_module, Init)// Usage from JavaScript
const native = require('./build/Release/native_module');
// 10x faster than JavaScript equivalent
const result = native.fibonacci(50);๋ค์ดํฐ๋ธ ๋ชจ๋์ ์ง์ค์ ์ธ ๊ณ์ฐ, ๊ธฐ์กด C/C++ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ํตํฉ, ๋๋ ์์คํ API ์ ๊ทผ์ ์ ์ฉํฉ๋๋ค.
์ง๋ฌธ 14: V8 Garbage Collector๋ฅผ ์ค๋ช ํ๋ผ
GC์ ์ดํด๋ ์ผ์ ์ ์ง์ ๋ฉ๋ชจ๋ฆฌ ์๋น๋ฅผ ์ต์ํํ๋ ์ฝ๋ ์์ฑ์ ๋์์ด ๋ฉ๋๋ค.
// V8 GC uses two spaces: Young and Old Generation
// 1. Young Generation: short-lived objects
function shortLivedObjects() {
for (let i = 0; i < 1000; i++) {
const temp = { data: i }; // Allocated then collected quickly
}
// Minor GC (Scavenge) very fast
}
// 2. Old Generation: objects that survive multiple GCs
const cache = new Map(); // Survives, promoted to Old Generation
// โ Problematic pattern: many promoted objects
function createManyLongLived() {
const objects = [];
for (let i = 0; i < 100000; i++) {
objects.push({ id: i, data: new Array(100).fill(0) });
}
return objects; // All promoted to Old Gen = slow major GC
}
// โ
Optimized pattern: object reuse
class ObjectPool {
constructor(factory, size = 100) {
this.pool = Array.from({ length: size }, factory);
this.available = [...this.pool];
}
acquire() {
return this.available.pop() || this.pool[0];
}
release(obj) {
// Reset and return to pool
Object.keys(obj).forEach(k => obj[k] = null);
this.available.push(obj);
}
}
// GC monitoring
const v8 = require('v8');
function getHeapStats() {
const stats = v8.getHeapStatistics();
return {
totalHeap: `${Math.round(stats.total_heap_size / 1024 / 1024)}MB`,
usedHeap: `${Math.round(stats.used_heap_size / 1024 / 1024)}MB`,
heapLimit: `${Math.round(stats.heap_size_limit / 1024 / 1024)}MB`,
};
}--max-old-space-size ํ๋๊ทธ๋ก ๋ฉ๋ชจ๋ฆฌ ์ง์ฝ์ ์ ํ๋ฆฌ์ผ์ด์
์ Old Generation ์ ํ์ ๋๋ฆด ์ ์์ต๋๋ค.
์ง๋ฌธ 15: ๊ทธ๋ ์ด์คํ ์ ง๋ค์ด์ ๊ตฌํํ๋ ๋ฐฉ๋ฒ์?
๊ทธ๋ ์ด์คํ ์ ง๋ค์ด์ ์งํ ์ค์ธ ์์ฒญ์ ์๋ฃํ๊ณ ์๋ฒ ์ค์ง ์ ์ ์ฐ๊ฒฐ์ ์ ์ ํ ๋ซ๋ ๊ฒ์ ๊ฐ๋ฅํ๊ฒ ํฉ๋๋ค.
const http = require('http');
const server = http.createServer((req, res) => {
// Simulate a long request
setTimeout(() => {
res.writeHead(200);
res.end('Done');
}, 2000);
});
// Tracking active connections
let connections = new Set();
server.on('connection', (conn) => {
connections.add(conn);
conn.on('close', () => connections.delete(conn));
});
// Graceful shutdown function
async function shutdown(signal) {
console.log(`${signal} received, starting graceful shutdown...`);
// 1. Stop accepting new connections
server.close(() => {
console.log('HTTP server closed');
});
// 2. Close idle connections
for (const conn of connections) {
conn.end();
}
// 3. Close DB connections, queues, etc.
await Promise.all([
database.disconnect(),
redisClient.quit(),
messageQueue.close(),
]);
// 4. Safety timeout
setTimeout(() => {
console.error('Forced shutdown after timeout');
process.exit(1);
}, 30000);
console.log('Graceful shutdown completed');
process.exit(0);
}
// Listen for termination signals
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
// Start server
server.listen(3000, () => {
console.log('Server running on port 3000');
});์ปจํ ์ด๋(Docker, Kubernetes)๋ฅผ ์ฌ์ฉํ๋ ํ๋ก๋์ ํ๊ฒฝ์์ ๊ทธ๋ ์ด์คํ ์ ง๋ค์ด์ ๋ฌด์ค๋จ ๋ฐฐํฌ์ ํ์์ ์ ๋๋ค.
Node.js / NestJS ๋ฉด์ ์ค๋น๊ฐ ๋์ จ๋์?
์ธํฐ๋ํฐ๋ธ ์๋ฎฌ๋ ์ดํฐ, flashcards, ๊ธฐ์ ํ ์คํธ๋ก ์ฐ์ตํ์ธ์.
ํ๋ ์ง๋ฌธ
์ง๋ฌธ 16: ํด๊ฒฐํ ์ฑ๋ฅ ๋ฌธ์ ๋ฅผ ์ค๋ช ํ๋ผ
์ด ์ง๋ฌธ์ ์ค๋ฌด ๊ฒฝํ์ ํ๊ฐํฉ๋๋ค. STAR ํ์(์ํฉ, ๊ณผ์ , ํ๋, ๊ฒฐ๊ณผ)์ผ๋ก ๋ต๋ณ์ ๊ตฌ์ฑํ๋ ๊ฒ์ด ๊ถ์ฅ๋ฉ๋๋ค.
๊ตฌ์กฐํ๋ ๋ต๋ณ ์์:
Situation: A reporting API was timing out on requests
exceeding 100,000 records.
Task: Reduce response time from 45s to under 5s.
Action:
1. Profiling with clinic.js โ identified JSON serialization as bottleneck
2. Implemented streaming with Transform streams
3. Database-side pagination
4. Added Redis caching for frequent queries
Result: Response time reduced to 2s, memory usage decreased by 10x.์ง๋ฌธ 17: ์์กด์ฑ๊ณผ ๊ทธ ์ ๋ฐ์ดํธ๋ฅผ ์ด๋ป๊ฒ ๊ด๋ฆฌํ๋๊ฐ?
{
"dependencies": {
// โ
Exact versions for production
"express": "4.18.2",
// โ
Caret for compatible minor updates
"lodash": "^4.17.21",
// โ Avoid latest or *
// "some-lib": "*"
},
"devDependencies": {
// Quality tools
"npm-check-updates": "^16.0.0"
},
"scripts": {
// Vulnerability check
"audit": "npm audit --audit-level=moderate",
// Interactive update
"update:check": "ncu",
"update:apply": "ncu -u && npm install"
},
"engines": {
// Specify required Node.js version
"node": ">=20.0.0"
}
}package-lock.json ์ฌ์ฉ, Dependabot ๋๋ Renovate๋ฅผ ํตํ ์๋ํ, ๊ฐ ๋ฉ์ด์ ์
๋ฐ์ดํธ ์ ํ๊ท ํ
์คํธ๋ฅผ ์ธ๊ธํ๋ ๊ฒ์ด ๊ถ์ฅ๋ฉ๋๋ค.
๊ฒฐ๋ก
Node.js ๋ฐฑ์๋ ๋ฉด์ ์์๋ ๋ด๋ถ ๋ฉ์ปค๋์ฆ์ ์ด๋ก ์ ์ดํด์ ํ๋ก๋์ ํ๊ฒฝ์ ์ค์ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋ ๋ฅ๋ ฅ์ด ๋ชจ๋ ํ๊ฐ๋ฉ๋๋ค. Event Loop, ๋น๋๊ธฐ ํจํด, ์ต์ ํ ๊ธฐ๋ฒ์ ์๋ฌ์ ์๋์ด ๋ฐฑ์๋ ๊ฐ๋ฐ์ ํฌ์ง์ ์์ ๊ธฐ๋๋๋ ๊ธฐ๋ฐ์ ํ์ฑํฉ๋๋ค.
์ค๋น ์ฒดํฌ๋ฆฌ์คํธ
- โ Event Loop์ ๋์๊ณผ ๊ทธ ๋จ๊ณ๋ฅผ ์ดํดํ๋ค
- โ ์ฝ๋ฐฑ, Promise, async/await์ ์ฐจ์ด๋ฅผ ์๋ฌํ๋ค
- โ ๋น๋๊ธฐ ์ค๋ฅ ์ฒ๋ฆฌ ํจํด์ ์๋ค
- โ Streams์ ํด๋์ ๋ฉ์๋์ ์ฌ์ฉ ์์ ์ ์๋ค
- โ ๋ฉ๋ชจ๋ฆฌ ๋์๋ฅผ ์๋ณํ๊ณ ์์ ํ๋ค
- โ OWASP ๋ณด์ ๋ชจ๋ฒ ์ฌ๋ก๋ฅผ ์ ์ฉํ๋ค
- โ ํด๋ฌ์คํฐ๋ง๊ณผ ๊ทธ๋ ์ด์คํ ์ ง๋ค์ด์ ๊ตฌํํ๋ค
- โ ํ๋กํ์ผ๋ง ๋๊ตฌ(clinic.js, Chrome DevTools)๋ฅผ ์ฌ์ฉํ๋ค
์ฐ์ต์ ์์ํ์ธ์!
๋ฉด์ ์๋ฎฌ๋ ์ดํฐ์ ๊ธฐ์ ํ ์คํธ๋ก ์ง์์ ํ ์คํธํ์ธ์.
๊ธฐ์ ์ ์ค๋น๋ ์ค์ ํ๋ก์ ํธ๋ก ๋ณด์ํด์ผ ํฉ๋๋ค. ํ๋ก๋์ API ๊ตฌ์ถ, Node.js ์คํ์์ค ํ๋ก์ ํธ ๊ธฐ์ฌ, LeetCode ๊ฐ์ ํ๋ซํผ์์์ ๋ฌธ์ ํ์ด๊ฐ ์ด๋ฌํ ์ง์์ ๊ฒฌ๊ณ ํ ํ๋ ๋ฐ ๋์์ด ๋ฉ๋๋ค.
ํ๊ทธ
๊ณต์
๊ด๋ จ ๊ธฐ์ฌ

NestJS + Prisma: Node.js๋ฅผ ์ํ ๋ชจ๋ ๋ฐฑ์๋ ์คํ
NestJS์ Prisma๋ก ๋ชจ๋ํ ๋ฐฑ์๋ API๋ฅผ ๊ตฌ์ถํ๊ธฐ ์ํ ์์ ํ ๊ฐ์ด๋์ ๋๋ค. ์ค์ , ๋ชจ๋ธ, ์๋น์ค, ํธ๋์ญ์ ๋ฐ ๋ชจ๋ฒ ์ฌ๋ก๋ฅผ ์ค๋ช ํฉ๋๋ค.

NestJS: ์์ ํ REST API ๊ตฌ์ถ ๊ฐ์ด๋
NestJS๋ก ์ ๋ฌธ์ ์ธ REST API๋ฅผ ๊ตฌ์ถํ๋ ์๋ฒฝ ๊ฐ์ด๋์ ๋๋ค. ์ปจํธ๋กค๋ฌ, ์๋น์ค, ๋ชจ๋ ๊ตฌ์ฑ, class-validator๋ฅผ ํ์ฉํ ์ ํจ์ฑ ๊ฒ์ฌ, ์๋ฌ ํธ๋ค๋ง์ ์ค์ ์ฝ๋๋ก ์ค๋ช ํฉ๋๋ค.

Node.js 24 ํต์ฌ ๊ธฐ๋ฅ ์์ ๋ถ์: URLPattern, ํผ๋ฏธ์ ๋ชจ๋ธ, ๋ฉด์ ๋๋น ๊ฐ์ด๋ (2026๋ ํ)
Node.js 24 LTS(Krypton)์ ์ฃผ์ ์ ๊ธฐ๋ฅ์ธ URLPattern, ํผ๋ฏธ์ ๋ชจ๋ธ, ๋ช ์์ ๋ฆฌ์์ค ๊ด๋ฆฌ๋ฅผ ์ค์ ์ฝ๋ ์์ ์ ๋ฉด์ ๋๋น ์ง๋ฌธ์ผ๋ก ์์ธํ๊ฒ ๋ถ์ํ๋ค.