Topic01 / 55
Introduction to Node.js
What & Why
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
1// index.js — a basic HTTP server
2const http = require('http'); // CommonJS (older)
3import http from 'http'; // ES Modules (modern, use .mjs or "type":"module")
4
5const server = http.createServer((req, res) => {
6 res.writeHead(200, { 'Content-Type': 'application/json' });
7 res.end(JSON.stringify({ message: 'Hello from Node.js!' }));
8});
9
10server.listen(3000, () => {
11 console.log('Server running on http://localhost:3000');
12});Real-World Example
A simple API server returning system stats:
example.ts
javascript
1import http from 'http';
2import os from 'os';
3
4const server = http.createServer((req, res) => {
5 if (req.url === '/health' && req.method === 'GET') {
6 const stats = {
7 status: 'healthy',
8 uptime: `${Math.floor(process.uptime())}s`,
9 memory: {
10 used: `${Math.round(process.memoryUsage().heapUsed / 1024 / 1024)}MB`,
11 total: `${Math.round(os.totalmem() / 1024 / 1024 / 1024)}GB`
12 },
13 platform: os.platform(),
14 nodeVersion: process.version,
15 };
16
17 res.writeHead(200, { 'Content-Type': 'application/json' });
18 res.end(JSON.stringify(stats, null, 2));
19 } else {
20 res.writeHead(404);
21 res.end('Not Found');
22 }
23});
24
25server.listen(process.env.PORT || 3000);Pitfalls & Interview Tips
- ⚠️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.