Node.js is widely used to create high-performance, scalable servers for web applications, APIs and real-time systems. Its non-blocking, event-driven architecture makes it an excellent choice for building efficient servers.
What Is a Node.js Server?
A Node.js server is an application built using Node.js to handle incoming client requests and send appropriate responses. It leverages the http module, which is part of Node.js’s built-in modules, to create web servers.
Key Features of a Node.js Server:
- Asynchronous I/O: Handles multiple requests without blocking the execution thread.
- Event-Driven Architecture: Efficiently manages client-server interactions.
- Scalability: Handles thousands of concurrent connections with minimal resource usage.
Step 1: Setting Up a Basic Node.js Server
Create a Simple HTTP Server
The http module allows you to create an HTTP server with just a few lines of code.
Code Example: Simple Node.js Server
const http = require('http');
// Create an HTTP server
const server = http.createServer((req, res) => {
// Set the response header
res.writeHead(200, { 'Content-Type': 'text/plain' });
// Send a response
res.end('Hello, World!');
});
// Start the server on port 3000
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Explanation:
- http.createServer(): Creates the server instance and handles client requests.
- req (Request): Represents the client’s request.
- res (Response): Represents the server’s response to the client.
- server.listen(3000): Starts the server on port 3000.
Step 2: Adding Routing to Your Server
Routing is the process of determining how the server should respond based on the requested URL.
Code Example: Node.js Server with Routing
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Welcome to the Home Page');
} else if (req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('About Us Page');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});
// Start the server
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Explanation:
- req.url: Retrieves the URL of the incoming request.
- The server responds with different content based on the URL (
/
, /about, etc.).
Step 3: Handling JSON Data
A Node.js server can process JSON data sent by the client, making it ideal for APIs.
Code Example: Node.js Server Handling JSON
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/data') {
let body = '';
// Collect incoming data
req.on('data', chunk => {
body += chunk.toString();
});
// Process the data when fully received
req.on('end', () => {
const jsonData = JSON.parse(body);
console.log('Received data:', jsonData);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Data received successfully' }));
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});
// Start the server
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Explanation:
- req.method: Checks if the request is a POST request.
- req.on(‘data’): Listens for incoming chunks of data.
- JSON.parse(): Converts the string data into a JSON object.
Step 4: Serving Static Files
A Node.js server can also serve static files like HTML, CSS, and images using the fs module.
Code Example: Serving Static HTML Files
const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
if (req.url === '/') {
fs.readFile('index.html', (err, data) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});
// Start the server
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Step 5: Using Express.js for Simplified Server Development
While the http module is powerful, frameworks like Express.js simplify server development by offering built-in routing, middleware, and utility functions.
Code Example: Simple Server Using Express.js
const express = require('express');
const app = express();
// Middleware to parse JSON data
app.use(express.json());
// Define routes
app.get('/', (req, res) => {
res.send('Welcome to the Express Server!');
});
app.post('/data', (req, res) => {
console.log('Received JSON:', req.body);
res.json({ message: 'Data received successfully' });
});
// Start the server
app.listen(3000, () => {
console.log('Express server running on http://localhost:3000');
});
Key Advantages of Using Node.js for Servers
- Asynchronous and Non-Blocking:
Handles multiple requests efficiently without waiting for previous requests to complete. - Scalability:
Ideal for high-concurrency scenarios like chat apps and real-time APIs. - Rich Ecosystem:
The npm ecosystem offers thousands of modules for added functionality. - Cross-Platform:
Node.js works seamlessly on Windows, Linux, and macOS.
Real-World Applications
- Web Applications:
Build dynamic websites using Node.js and Express.js. - REST APIs:
Create scalable APIs for mobile apps and web applications. - Real-Time Apps:
Develop chat applications, live notifications, or collaborative tools using WebSockets. - IoT Systems:
Use Node.js to collect and process data from IoT devices.