use static pages nodejs
To create a static file server using Node.js, you can use the built-in 'http' and 'fs' modules. Here are the steps:
- Import the required modules:
const http = require('http');
const fs = require('fs');
const path = require('path');
- Create a server and define the port to listen on:
const server = http.createServer((req, res) => {
// Handle requests here
});
const port = 3000;
server.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
- Handle incoming requests and serve static files:
const server = http.createServer((req, res) => {
let filePath = '.' + req.url;
if (filePath === './') {
filePath = './index.html';
}
const extname = path.extname(filePath);
let contentType = 'text/html';
fs.readFile(filePath, (err, content) => {
if (err) {
if (err.code === 'ENOENT') {
fs.readFile('./404.html', (err, content) => {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
});
} else {
res.writeHead(500);
res.end(`Server Error: ${err.code}`);
}
} else {
if (extname === '.js') {
contentType = 'text/javascript';
} else if (extname === '.css') {
contentType = 'text/css';
}
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
});
- Run the server and test it by accessing static files in the browser.
That's it! You've now created a basic static file server using Node.js.