🧠 Node.
js: Letting JavaScript Handle Web Requests
🎯 The Goal
Write JavaScript code that:
• Receives an incoming message (e.g., user opening twitter.com).
• Inspects the message (looks at what it’s asking for).
• Sends back the appropriate response (e.g., tweets, HTML, data).
🧩 The Problem
JavaScript can’t directly:
• Access the network card.
• Receive HTTP messages.
🧰 The Solution: Node.js + Built-in Modules
• Node.js provides features written in C++ that interface with the OS/network.
• JavaScript accesses those C++ features using special labels (built-in identifiers).
These labels in JavaScript are linked to actual Node C++ features.
🌐 Handling Web Requests
To receive HTTP messages, Node provides a special module:
• http → accesses the network and handles HTTP-formatted messages.
When you type a URL and press enter:
• Your browser sends a message in HTTP format (HyperText Transfer Protocol).
• It's a structured request asking for a webpage, file, etc.
🔌 Sockets: Opening a Channel
• To receive messages, we must open a socket (an open two-way internet connection).
• This is done using Node's http module.
💡 JavaScript + Node’s HTTP Module
You write something like:
js
CopyEdit
const http = require('http');
const server = http.createServer((req, res) => {
// `req` = incoming request object
// `res` = response object you send back
res.end('Hello from Node.js');
});
server.listen(3000); // Open socket on port 3000
• http.createServer(...) is the JavaScript label that:
• Triggers C++ code in Node
• Opens the socket
• Tells JavaScript what code to run when a request is received
⚠️ Note on Accessing the http Label
• This label isn’t magically available like setTimeout in the browser.
• You must explicitly import it:
js
CopyEdit
const http = require('http');
🔁 Reusable Mental Model
Will’s emphasis:
This model applies to almost every Node.js feature.
• You use a JavaScript label (like http, fs, net)
• That label triggers a Node C++ feature
• The feature accesses a system-level capability (network, file system, etc.)