| Here's a simple Node.js example that demonstrates a basic HTTP server: Basic HTTP Server in Node.js // Load the http module to create an HTTP server.
const http = require('http');
// Configure the HTTP server to respond with "Hello, World!" to all requests.
const server = http.createServer((req, res) => {
// Set the response HTTP header with HTTP status and Content type
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
// Listen on port 8080, IP defaults to 127.0.0.1
server.listen(8080, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:8080/');
});
How it works: - http module: This module is built into Node.js and provides the functionality to create an HTTP server.
- http.createServer(): This function creates a new HTTP server and takes a callback function that will be executed each time a request is received. The callback function receives two arguments:
req: An object containing information about the request (e.g., URL, headers, etc.).res: An object that can be used to send a response back to the client.
- server.listen(): This method makes the server listen for incoming connections on a specified port (3000 in this case).
Running the example: - Save the code to a file, e.g.,
server.js. Run the server using Node.js: node server.js
- Open a browser and go to
http://127.0.0.1:8080/ to see the message "Hello, World!".
If you want to use local files, you can serve local files like index.html or images using Node.js. To do this, you'll typically want to use the fs (File System) module to read the files and serve them via the HTTP server. Here's an example that serves an index.html file and images from the local filesystem: Example: Serving Local Files with Node.js Directory Structure: /myapp
├── server.js
├── index.html
└── images
└── logo.png
index.html (Example)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Node.js Server</title>
</head>
<body>
<h1>Hello from Node.js!</h1>
<img src="/images/logo.png" alt="Logo">
</body>
</html>
server.js
const http = require('http');
const fs = require('fs');
const path = require('path');
// MIME types mapping for different file extensions
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.json': 'application/json',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.eot': 'application/vnd.ms-fontobject',
'.otf': 'font/otf',
'.wasm': 'application/wasm'
};
// Create an HTTP server
const server = http.createServer((req, res) => {
// Normalize URL by removing querystring, optional slashes, and making it lowercase
let filePath = '.' + req.url;
if (filePath == './') {
filePath = './index.html';
}
// Determine the content type based on the file extension
const extname = String(path.extname(filePath)).toLowerCase();
const contentType = mimeTypes[extname] || 'application/octet-stream';
// Read the requested file from the filesystem
fs.readFile(filePath, (error, content) => {
if (error) {
if (error.code == 'ENOENT') {
// File not found
fs.readFile('./404.html', (err, content) => {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
});
} else {
// Some server error
res.writeHead(500);
res.end(`Server Error: ${error.code}`);
}
} else {
// Serve the file
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
});
// Listen on port 8080
server.listen(8080, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:8080/');
});
How it works: - File Path Normalization: The code normalizes the requested file path by stripping out any query strings and adding a default to
index.html if no file is specified. - MIME Type Detection: The content type (MIME type) is determined based on the file extension to ensure the correct type is sent in the response headers.
- File Reading: The
fs.readFile() method reads the file from the local filesystem and serves it. If the file is not found, a 404.html file (if it exists) is served instead.
Running the Example: - Save the code to
server.js. - Ensure you have an
index.html file and any other files (like images) in the correct directory. Run the server using Node.js: node server.js
- Visit
http://127.0.0.1:8080/ in your browser. You should see the HTML file and any linked images or other assets being served. |