Introduction to Node.js
- Node.js runs JavaScript outside the browser using Google's V8 engine.
- Single-threaded event loop with non-blocking I/O — efficient for many concurrent I/O operations.
- CPU-intensive tasks block the event loop — use worker_threads for computation, not for waiting on I/O.
Node.js is a JavaScript runtime built on Chrome's V8 engine that runs outside the browser. It uses a single-threaded event loop with non-blocking I/O — instead of waiting for a file read or database query to finish, Node registers a callback and handles other requests in the meantime. This makes it efficient for I/O-heavy workloads like APIs.
How Node.js Handles Concurrency
Traditional servers, like Apache, create one thread per connection. This consumes significant memory as the number of users grows. Node.js takes a different approach: it uses a single main thread and an Event Loop. When an I/O operation (like a database query or file read) is initiated, Node hands the task off to the system kernel or a background thread pool (Libuv). The main thread remains free to handle new incoming requests immediately.
This 'non-blocking' nature is why a single Node.js instance can out-perform traditional multi-threaded servers in I/O-bound scenarios.
/* * Package: io.thecodeforge.node.basics */ const fs = require('fs'); console.log('1. Initiating non-blocking file read...'); // fs.readFile is asynchronous and non-blocking fs.readFile('large-report.pdf', (err, data) => { if (err) { console.error('Error reading file:', err.message); return; } // This runs only when the OS finishes the heavy lifting console.log(`3. Success! Processed ${data.length} bytes.`); }); // This executes while the file is still being read by the OS console.log('2. Main thread is free! Handling other user requests...');
2. Main thread is free! Handling other user requests...
3. Success! Processed 45210 characters.
Building a Production-Ready HTTP Server
While frameworks like Express are the industry standard, understanding the native http module is essential for grasping how Node.js communicates with the outside world. Every request is a stream, and every response is a stream.
/* * Package: io.thecodeforge.node.web */ const http = require('http'); const PORT = process.env.PORT || 3000; const server = http.createServer((req, res) => { const { method, url } = req; // Standard REST routing logic if (method === 'GET' && url === '/') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: 'success', message: 'Welcome to TheCodeForge API' })); } else if (method === 'GET' && url === '/health') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('UP'); } else { res.writeHead(404, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Endpoint Not Found' })); } }); server.listen(PORT, () => { console.log(`[TheCodeForge] Server ignited on port ${PORT}`); });
Modules — CommonJS and ES Modules
Node.js originally popularized CommonJS (require), but the industry has moved toward the official JavaScript standard: ES Modules (import/export). Choosing the right one impacts how your code is bundled and optimized.
/* * Package: io.thecodeforge.node.modules */ // --- CommonJS (Standard in older Node apps) --- // utils.js -> module.exports = { log: (msg) => console.log(msg) }; // app.js -> const { log } = require('./utils'); // --- ES Modules (Recommended for new projects) --- // In package.json, set "type": "module" import os from 'os'; import { networkInterfaces } from 'os'; const systemMetrics = { platform: os.platform(), freeMem: (os.freemem() / 1024 / 1024 / 1024).toFixed(2) + ' GB', uptime: (os.uptime() / 3600).toFixed(1) + ' hours' }; console.log('System Status:', systemMetrics);
🎯 Key Takeaways
- Node.js runs JavaScript outside the browser using Google's V8 engine.
- Single-threaded event loop with non-blocking I/O — efficient for many concurrent I/O operations.
- CPU-intensive tasks block the event loop — use worker_threads for computation, not for waiting on I/O.
- CommonJS (require/module.exports) is the traditional module system. ES Modules (import/export) are the modern standard.
- npm is Node's package manager — package.json describes your project's dependencies and scripts.
Interview Questions on This Topic
- QExplain the phases of the Node.js Event Loop. Where does process.nextTick() fit into these phases?
- QWhy is Node.js considered 'unsuitable' for heavy data crunching, and how would you architect a solution to handle it anyway?
- QLeetCode Scenario: Given an array of 1,000 file paths, write a script to read them all in parallel using Node.js but limit the concurrency to 5 at a time to avoid OS file handle exhaustion.
- QCompare and contrast the behavior of 'require()' vs 'import' regarding synchronous/asynchronous loading and top-level await.
- QWhat is 'Callback Hell' and how do Promises or Async/Await resolve the underlying architectural issues in Node.js applications?
Frequently Asked Questions
Is Node.js good for CPU-intensive tasks?
Generally, no. Because Node.js is single-threaded, a heavy CPU operation (like image processing or complex math) will block the Event Loop, making the server unresponsive to other users. For these cases, we use the worker_threads module to run tasks on background threads, or offload them to a specialized microservice.
What is the difference between Node.js and a browser JavaScript environment?
Node.js has access to the OS (file system, hardware, environment variables) but lacks the DOM and window object. Conversely, the browser has the DOM for UI manipulation but is 'sandboxed' from the file system for security. Both use the same V8 engine to interpret JavaScript code.
What is Libuv and why does Node.js need it?
Libuv is a C library that Node.js uses to handle its asynchronous I/O operations. It manages the Event Loop and the thread pool used for tasks that cannot be handled by the OS kernel directly (like disk access and DNS lookups).
Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.