Topic 1 of 55
Node.js
Overview
Node.js is a JavaScript runtime built on Chrome's V8 engine that lets you run JavaScript on the server. Its non-blocking, event-driven architecture makes it ideal for I/O-intensive applications — REST APIs, real-time apps, and microservices.
Syntax
javascript
// index.js — a basic HTTP server
const http = require('http'); // CommonJS (older)
import http from 'http'; // ES Modules (modern, use .mjs or "type":"module")
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Hello from Node.js!' }));
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});Common Pitfalls
- Node.js is single-threaded — a blocking operation (heavy CPU work) freezes ALL requests. Use Worker Threads for CPU-intensive tasks.
- Never mix CommonJS (require) and ES Modules (import) in the same project without careful configuration.
- Interview tip: Node.js uses libuv under the hood for its event loop and async I/O — not the browser's event loop. Same concept, different implementation.
Real-World Example
A simple API server returning system stats:
example
javascript
import http from 'http';
import os from 'os';
const server = http.createServer((req, res) => {
if (req.url === '/health' && req.method === 'GET') {
const stats = {
status: 'healthy',
uptime: `${Math.floor(process.uptime())}s`,
memory: {
used: `${Math.round(process.memoryUsage().heapUsed / 1024 / 1024)}MB`,
total: `${Math.round(os.totalmem() / 1024 / 1024 / 1024)}GB`
},
platform: os.platform(),
nodeVersion: process.version,
};
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(stats, null, 2));
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(process.env.PORT || 3000);