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.
Node JavaScript Runtime
A server-side JavaScript runtime based on the V8 engine. Builds high-performance web servers with event-driven asynchronous I/O.
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.
// 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}/`);
});
// 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/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('λͺ¨λ μμ
μλ£'));
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."
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."
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
Nested callbacks reduce readability and maintainability. Use async/await or Promise chaining to write asynchronous code in a synchronous style. You can convert callback-based APIs to Promises with util.promisify().
Asynchronous errors must be caught with try-catch. Because unhandled Promise rejections can terminate the process, set up process.on('unhandledRejection'), and be sure to add an error-handling middleware in Express.
Prevent SQL Injection by using Prepared Statements or an ORM (Prisma, Sequelize). For XSS attacks, always escape user input and set security headers with the helmet middleware. CSRF tokens are also essential.
When installing npm packages, scan for security vulnerabilities with npm audit. Remove unnecessary packages, and include package-lock.json in version control to ensure consistent builds.