πŸ’» Programming

Node.js

Node JavaScript Runtime

A server-side JavaScript runtime based on the V8 engine. Builds high-performance web servers with event-driven asynchronous I/O.

πŸ“– Detailed Explanation

Node.js is a server-side JavaScript runtime environment built on Google Chrome's V8 JavaScript engine. By making it possible to run JavaScript on the server, which previously could only be run in web browsers, it enabled full-stack JavaScript development, in which the frontend and backend can be developed in the same language. The V8 engine compiles JavaScript code into native machine code to deliver excellent execution performance.

Node.js was developed by Ryan Dahl in 2009. Dahl, who was concerned about the limits of the Apache server in handling concurrent connections and the inefficiency of the blocking I/O model, solved this problem by adopting an asynchronous, event-driven architecture. Since it was first presented at JSConf EU 2009, it has grown rapidly, and it is now managed by the OpenJS Foundation and has become established as a core backend technology used by millions of developers worldwide.

The core feature of Node.js is the Event Loop and asynchronous I/O model. Although it runs on a single thread, it handles I/O operations in a non-blocking manner through the event loop. It does not wait until I/O operations such as file reads and network requests are complete, but immediately processes the next task, and executes a callback function when the I/O completes. Thanks to this architecture, it can efficiently handle tens of thousands of simultaneous connections, making it well suited for real-time applications.

At the center of the Node.js ecosystem is npm (Node Package Manager). npm is the world's largest open-source package registry, with more than 2 million packages registered. A wide variety of packages can be used, from web frameworks such as Express.js and NestJS to database drivers and utility libraries, which greatly improves development productivity. Global companies such as Netflix, LinkedIn, Uber, and PayPal use Node.js in production environments.

πŸ’» Code Example

server.js - Basic HTTP server
// Node.js λ‚΄μž₯ http λͺ¨λ“ˆλ‘œ κ°„λ‹¨ν•œ μ›Ή μ„œλ²„ 생성
const http = require('http');

// μ„œλ²„ μ„€μ •
const hostname = '127.0.0.1';
const port = 3000;

// HTTP μ„œλ²„ 생성 - 비동기 μš”μ²­ 처리
const server = http.createServer((req, res) => {
    // 응닡 헀더 μ„€μ •
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain; charset=utf-8');

    // URL에 λ”°λ₯Έ λΌμš°νŒ…
    if (req.url === '/') {
        res.end('μ•ˆλ…•ν•˜μ„Έμš”! Node.js μ„œλ²„μž…λ‹ˆλ‹€.');
    } else if (req.url === '/api') {
        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify({ message: 'API 응닡', status: 'success' }));
    } else {
        res.statusCode = 404;
        res.end('νŽ˜μ΄μ§€λ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€.');
    }
});

// μ„œλ²„ μ‹œμž‘
server.listen(port, hostname, () => {
    console.log(`μ„œλ²„ μ‹€ν–‰ 쀑: http://${hostname}:${port}/`);
});
app.js - Express.js REST API
// Express.jsλ₯Ό μ‚¬μš©ν•œ RESTful API μ„œλ²„
const express = require('express');
const app = express();
const port = 3000;

// JSON νŒŒμ‹± 미듀웨어
app.use(express.json());

// μƒ˜ν”Œ 데이터
let users = [
    { id: 1, name: 'κΉ€μ² μˆ˜', email: 'kim@example.com' },
    { id: 2, name: '이영희', email: 'lee@example.com' }
];

// GET - λͺ¨λ“  μ‚¬μš©μž 쑰회
app.get('/api/users', (req, res) => {
    res.json(users);
});

// GET - νŠΉμ • μ‚¬μš©μž 쑰회
app.get('/api/users/:id', (req, res) => {
    const user = users.find(u => u.id === parseInt(req.params.id));
    if (!user) return res.status(404).json({ error: 'μ‚¬μš©μžλ₯Ό 찾을 수 μ—†μŠ΅λ‹ˆλ‹€' });
    res.json(user);
});

// POST - μƒˆ μ‚¬μš©μž 생성
app.post('/api/users', (req, res) => {
    const newUser = {
        id: users.length + 1,
        name: req.body.name,
        email: req.body.email
    };
    users.push(newUser);
    res.status(201).json(newUser);
});

// μ„œλ²„ μ‹œμž‘
app.listen(port, () => {
    console.log(`Express μ„œλ²„ μ‹€ν–‰ 쀑: http://localhost:${port}`);
});
async.js - async/await pattern
// async/awaitλ₯Ό μ‚¬μš©ν•œ 비동기 처리 (콜백 μ§€μ˜₯ λ°©μ§€)
const fs = require('fs').promises;

// 파일 읽기 + API 호좜 순차 처리
async function processData() {
    try {
        // 1. μ„€μ • 파일 읽기
        const config = JSON.parse(
            await fs.readFile('./config.json', 'utf-8')
        );
        console.log('μ„€μ • λ‘œλ“œ μ™„λ£Œ:', config.apiUrl);

        // 2. API 호좜 (fetchλŠ” Node 18+)
        const response = await fetch(config.apiUrl);
        const data = await response.json();
        console.log('API 데이터 μˆ˜μ‹ :', data.length, '건');

        // 3. κ²°κ³Ό 파일 μ €μž₯
        await fs.writeFile(
            './output.json',
            JSON.stringify(data, null, 2)
        );
        console.log('파일 μ €μž₯ μ™„λ£Œ');

        return data;
    } catch (error) {
        // μ—λŸ¬ 핸듀링
        console.error('처리 쀑 였λ₯˜ λ°œμƒ:', error.message);
        throw error;
    }
}

// μ‹€ν–‰
processData().then(() => console.log('λͺ¨λ“  μž‘μ—… μ™„λ£Œ'));

πŸ—£οΈ Practical Conversation Examples

Technical Meeting Selecting the API Server Tech Stack

PM Manager Park:

"Let's discuss what technology to use to build the API server for this new project. Real-time notifications are the key feature."

Backend Associate Kim:

"I recommend Node.js. Socket.io integrates easily for real-time features, and thanks to its event-driven architecture, it has strengths in handling concurrent connections. Since the frontend is React, unifying on JavaScript would also allow code sharing."

Senior Developer Manager Lee:

"That's a good choice. However, if there are CPU-intensive tasks, we should also consider using Worker Threads or separating just that part into a separate microservice. I suggest starting with Express.js and migrating to NestJS as the scale grows."

PM Manager Park:

"How do we manage npm package security? I've heard that as dependencies increase, there are concerns about vulnerabilities."

Backend Associate Kim:

"You can run regular scans with npm audit and set up automatic monitoring with Snyk or Dependabot. You should also manage package-lock.json thoroughly to pin versions."

Technical Interview How the Event Loop Works

Interviewer:

"Please explain how Node.js, being single-threaded, can handle tens of thousands of concurrent requests."

Candidate:

"Node.js uses the event loop and non-blocking I/O. The main thread receives a request, delegates the I/O work to libuv's thread pool, and immediately processes the next request. When the I/O completes, a callback is registered in the event queue, and the event loop takes it out and executes it."

Interviewer:

"Could you also explain the phases of the event loop?"

Candidate:

"Yes, the event loop cycles through the timers, pending callbacks, idle/prepare, poll, check, and close callbacks phases. setTimeout runs in timers, I/O callbacks run in poll, and setImmediate runs in check. process.nextTick runs immediately after the current phase completes and has the highest priority."

Interviewer:

"What are the limitations of Node.js when there are many CPU-bound tasks, and how can they be addressed?"

Candidate:

"If a CPU task takes a long time, the event loop gets blocked and the processing of other requests is delayed. Solutions include parallel processing with Worker Threads, building a multi-process setup with cluster mode, or separating that task into a separate service."

Code Review Asynchronous Error Handling

Reviewer:

"This async function has no error handling. If an error occurs where you await, it becomes an unhandled rejection. From Node.js 15 onward, the process may even terminate."

Author:

"Would wrapping it in try-catch work? Or should I chain .catch()?"

Reviewer:

"With async/await, try-catch is the natural choice. Also, set up process.on('unhandledRejection') globally as well. If it's Express middleware, using the express-async-errors package automatically passes errors to the error handler."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Cautions

πŸ”— Related Terms

πŸ“š Learn More