Node.js Deep Dive
Node.js Deep Dive
Node.js is a JavaScript runtime built on Chrome's V8 engine that lets you run JavaScript outside the browser. Before Node.js existed, JavaScript could only run inside web browsers. Node.js changed that by taking the same V8 engine that Google Chrome uses and bundling it with a set of system-level APIs so JavaScript could read files, connect to networks, and interact with operating systems.
Released in 2009 by Ryan Dahl, Node.js has since become one of the most popular platforms for building web servers, command-line tools, and real-time applications.
How Node.js Works: The Event Loop
The most important concept in Node.js is the event loop. Unlike traditional server environments that create a new thread for every request (which is expensive), Node.js runs on a single thread and uses an event-driven, non-blocking input/output (I/O) model.
Here is how it works:
- Your Node.js program starts and registers event listeners (e.g., "when a request comes in, run this function").
- The event loop continuously checks if any events have occurred.
- When an event fires (a request arrives, a file finishes reading), the corresponding callback function is executed.
- While waiting for slow operations like file reads or database queries, Node.js does not block. It moves on and handles other events.
This makes Node.js extremely efficient for I/O-heavy applications like web servers and APIs.
// Demonstration of non-blocking I/O in Node.js
const fs = require('fs');
console.log('1. Starting file read...');
// This does NOT block. Node.js registers the callback and moves on.
fs.readFile('data.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err.message);
return;
}
console.log('3. File contents:', data);
});
console.log('2. This runs BEFORE the file is read!');
// Output order: 1, 2, 3 — because readFile is non-blocking
Node.js Core Modules
Node.js ships with built-in modules you can use without installing anything. These are called core modules.
| Module | Purpose |
|---|---|
fs | File System — read, write, delete files |
http | Create HTTP servers and clients |
path | Work with file and directory paths |
os | Get operating system information |
events | Build event-driven architectures |
crypto | Encryption, hashing, and security |
// Using the 'path' core module
const path = require('path');
const filePath = path.join('/users', 'amara', 'documents', 'report.txt');
console.log(filePath); // /users/amara/documents/report.txt
const ext = path.extname('server.js');
console.log(ext); // .js
const base = path.basename('/home/amara/server.js');
console.log(base); // server.js
// Using the 'os' core module
const os = require('os');
console.log('Platform:', os.platform()); // 'linux', 'darwin', 'win32'
console.log('CPU cores:', os.cpus().length);
console.log('Free memory (MB):', Math.round(os.freemem() / 1024 / 1024));
console.log('Home directory:', os.homedir());
CommonJS Modules vs ES Modules
Node.js originally used a module system called CommonJS (CJS). You have seen it with require() and module.exports. Modern JavaScript introduced ES Modules (ESM) with import and export syntax.
// CommonJS (traditional Node.js style)
const express = require('express');
const { readFile } = require('fs');
module.exports = { myFunction };
// ES Modules (modern style — requires "type": "module" in package.json)
import express from 'express';
import { readFile } from 'fs';
export { myFunction };
In this track we use CommonJS because it is more widely supported in Node.js tutorials and production code. You will encounter both in the real world.
Your First Node.js Server
You can create a working HTTP server with just Node.js core modules, no frameworks needed:
const http = require('http');
const server = http.createServer((req, res) => {
// Set the response status and headers
res.writeHead(200, { 'Content-Type': 'application/json' });
// Send a JSON response
const body = JSON.stringify({
message: 'Hello from Node.js!',
url: req.url,
method: req.method,
});
res.end(body);
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
Run this with node server.js and visit http://localhost:3000 in your browser.
The Global Object
In browsers, the global object is window. In Node.js, it is global. You can access it from anywhere in your code.
// Common global variables available in Node.js
console.log(__dirname); // Absolute path of the current directory
console.log(__filename); // Absolute path of the current file
console.log(process.env.NODE_ENV); // Current environment (development, production)
console.log(process.argv); // Command-line arguments passed to the script
// Setting an environment-specific value
process.env.PORT = '3000';
const port = parseInt(process.env.PORT) || 8080;
Key Takeaways
- Node.js runs JavaScript outside the browser using Google's V8 engine.
- The event loop allows Node.js to handle thousands of concurrent connections without blocking.
- Core modules like
fs,http, andpathare built in and need no installation. - CommonJS uses
require()andmodule.exports; ES Modules useimportandexport. - Node.js is ideal for I/O-intensive applications like APIs, chat servers, and real-time tools.
Practice Exercise
- Create a file called
info.jsthat uses theosmodule to log your platform, number of CPU cores, and home directory. - Create a simple HTTP server that returns a different JSON message depending on the request URL. For
/return{ "page": "home" }and for/aboutreturn{ "page": "about" }. - Add a
process.argvcheck so you can pass a custom port number when starting the server:node server.js 4000.
Try it yourself
Key Takeaways
- Node.js runs JavaScript on the server using the V8 engine, enabling JavaScript to be used for both frontend and backend development.
- The event loop is the core of Node.js — it lets a single thread handle thousands of concurrent connections by not blocking on I/O operations.
- Core modules like fs, http, path, and os are built into Node.js and require no installation.
- CommonJS (require/module.exports) is the traditional module system; ES Modules (import/export) are the modern standard.
- Non-blocking I/O is what makes Node.js fast and suitable for real-time applications and high-traffic APIs.
Quick Quiz
1.What JavaScript engine does Node.js use to run code?
2.What does 'non-blocking I/O' mean in Node.js?
3.Which Node.js core module would you use to read a file from disk?
4.What is the correct CommonJS syntax for importing a module in Node.js?
Ready to go further?
CareerEx gives you structured 12-week training, live classes every Saturday and Sunday, real tutor feedback, and a certificate. Join the next cohort.
Join CareerEx