Building a Node.js Server with Examples and Best Practices
Creating a Basic Server in Node.js
A Node.js server allows you to handle HTTP requests and responses, enabling web application development. Node.js uses its built-in http module to create servers without requiring external libraries. The http module provides the functionality to listen for incoming client requests, process them, and send appropriate responses.
This guide demonstrates how to build a basic server using Node.js, including handling routes, serving responses, and improving scalability.
Syntax:
The basic syntax for creating an HTTP server in Node.js is:
const http = require('http'); const server = http.createServer((req, res) => { // Request handling logic here }); server.listen(port, hostname, () => { // Callback when the server starts });
Examples and Code
1. A Basic Node.js Server
Code:
// Import the built-in http module
const http = require('http');
// Define the hostname and port for the server
const hostname = '127.0.0.1';
const port = 3000;
// Create the server
const server = http.createServer((req, res) => {
// Set the response header with status code and content type
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
// Send a response
res.end('Hello, World!\n');
});
// Start the server and listen on the defined hostname and port
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Explanation:
- http.createServer: Creates an HTTP server instance.
- req: Represents the incoming request object from the client.
- res: Represents the outgoing response object to the client.
- res.statusCode: Sets the HTTP status code (e.g., 200 for success).
- res.setHeader: Sets the response headers (e.g., Content-Type).
- res.end: Sends the response to the client and ends the request.
2. Handling Different Routes
Code:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end('<h1>Welcome to the Home Page</h1>');
} else if (req.url === '/about') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end('<h1>About Us</h1>');
} else {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/html');
res.end('<h1>404 - Page Not Found</h1>');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Explanation:
- req.url: Captures the URL path from the incoming request.
- The server provides different responses based on the URL (/, /about, etc.).
- 404 Handling: Responds with a 404 status code for unknown routes.
3. Serving JSON Data
Code:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
if (req.url === '/api') {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
const data = {
message: 'Hello, JSON!',
status: 'success',
};
res.end(JSON.stringify(data));
} else {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end('Not Found');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Explanation:
- Content-Type: application/json: Indicates the response is JSON data.
- JSON.stringify: Converts the JavaScript object into a JSON string for transmission.
Advanced Concepts
1. Using Express Framework:
While the http module is useful, frameworks like Express simplify server creation and routing.
Code:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
app.listen(port, () => {
console.log(`Express server running on http://localhost:${port}`);
});
2. Serving Static Files:
Use fs (File System) to serve HTML files or other static assets.
Key Notes
- Server Lifecycle: The server runs continuously and listens for requests until manually stopped using Ctrl+C.
- Error Handling: Always add error listeners to manage unexpected issues.
server.on('error', (err) => {
console.error('Server error:', err);
});
Best Practices
1. Use the http module for lightweight servers or prototypes.
2. For production-level applications, use a framework like Express for robust features and middleware.
3. Implement logging and error handling for better maintainability.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics