- Node.js Tutorial
- NodeJS Home
- NodeJS Introduction
- NodeJS Setup
- NodeJS First App
- NodeJS REPL
- NodeJS Command Line
- NodeJS NPM
- NodeJS Callbacks
- NodeJS Events
- NodeJS Event-Loop
- NodeJS Event-Emitter
- NodeJS Global-Objects
- NodeJS Console
- NodeJS Process
- NodeJS Buffers
- NodeJS Streams
- Node.js File Handling
- Node.js File System
- Node.js Read/Write File
- Working with folders in Node.js
- HTTP and Networking
- Node.js HTTP Module
- Anatomy of an HTTP Transaction
- Node.js MongoDB
- MongoDB Get Started
- MongoDB Create Database
- MongoDB Create Collection
- MongoDB Insert
- MongoDB Find
- MongoDB Query
- MongoDB Sort
- MongoDB Delete
- MongoDB Update
- MongoDB Limit
- MongoDB Join
- Node.js MySQL
- MySQL Get Started
- MySQL Create Database
- MySQL Create Table
- MySQL Insert Into
- MySQL Select From
- MySQL Where
- MySQL Order By
- MySQL Delete
- MySQL Update
- MySQL Join
- Node.js Modules
- Node.js Modules
- Node.js Built-in Modules
- Node.js Utility Modules
- Node.js Web Module
- Node.js Advanced
- Node.js Debugger
- Node.js Scaling Application
- Node.js Packaging
- Node.js Express Framework
- Node.js RESTFul API
- Node.js Useful Resources
- Node.js Useful Resources
- Node.js Discussion
Node.js Web Module
Node.js web modules are the building blocks that allow developers to transform a local JavaScript environment into a powerful web server. By leveraging built-in modules like http or external frameworks like Express, you can handle network requests, manage data flow, and build everything from simple websites to massive distributed APIs. Because Node.js is built on an event-driven, non-blocking I/O model, these web modules are incredibly efficient at handling thousands of concurrent connections.
Key Features of Web Modules
- HTTP Lifecycle Management: They facilitate the entire "Request-Response" cycle, allowing you to capture user data and send back appropriate content.
- Sophisticated Routing: Instead of manually parsing strings, web modules provide mechanisms to direct users to different "pages" or "endpoints" based on the URL.
- Middleware Support: This allows you to "plug in" functions that run before your main logic, such as authentication checks or logging.
- Scalability for APIs: Web modules make it easy to follow RESTful principles, allowing your application to communicate with mobile apps and other web services seamlessly.
Commonly Used Web Modules
- http: The foundational native module used to create basic servers. Most other web frameworks are actually built on top of this.
- https: A wrapper for the http module that uses TLS/SSL to provide a secure layer for data transmission.
- express: The "de facto" standard web framework for Node.js. It simplifies complex tasks like routing, template rendering, and session management.
- url: A utility module designed to break down a URL string into readable parts (like query parameters, paths, and protocols).
http module. Always use https to encrypt the data in transit.
Example Code
Using the http Module
The native http module is great for understanding how the web works at a low level. Every request provides a req object (what the user sent) and a res object (what you send back).
const http = require('http');
const server = http.createServer((req, res) => {
// Basic routing by checking the URL string
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Welcome to the Node.js Web Module!');
} else if (req.url === '/api/status') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'Online', uptime: process.uptime() }));
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Page not found');
}
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
res.end(). If you don't explicitly end the response, the user's browser will keep "spinning" until it eventually times out, as it thinks the server is still sending data.
Using the express Module
Express makes the code much cleaner and more readable, especially as your application grows to include dozens of routes.
// First, run 'npm install express' in your terminal
const express = require('express');
const app = express();
// Express handles the routing logic for you
app.get('/', (req, res) => {
res.send('Welcome to Express.js!');
});
app.get('/about', (req, res) => {
res.send('This is a much cleaner way to handle routing!');
});
app.listen(3000, () => {
console.log('Express server running on http://localhost:3000');
});
Using the url Module
When users search for something, like /search?term=javascript, you need the url module to extract that "term" value.
const url = require('url');
// Example of a typical URL found in an incoming request
const myURL = new URL('https://example.com:8080/products/search?category=electronics&sort=desc');
console.log('Protocol:', myURL.protocol); // https:
console.log('Host:', myURL.host); // example.com:8080
console.log('Pathname:', myURL.pathname); // /products/search
console.log('Category:', myURL.searchParams.get('category')); // electronics
new URL() constructor (WHATWG API) shown above rather than the older url.parse(), as it is more robust and follows the standard used by modern web browsers.
Summary
Node.js web modules provide the essential tools needed to build modern, high-performance web applications. While the native http module is excellent for learning and lightweight tasks, frameworks like Express build upon that foundation to provide the features needed for professional-grade APIs and websites. By mastering these modules and the URL utility, you can handle complex data routing and user interactions with just a few lines of JavaScript.