my-node-app/
├── app.js
├── data.json
└── utils.js
{
"message": "Hello from JSON!",
"status": "success"
}
// utils.js
function getCurrentTime() {
return new Date().toLocaleString();
}
module.exports = {
getCurrentTime
};
// app.js
const http = require(’http’);
const fs = require(’fs’);
const path = require(’path’);
const { getCurrentTime } = require(’./utils’);
const PORT = 3000;
const server = http.createServer((req, res) => {
const url = req.url;
if (url === ’/’) {
res.writeHead(200, { ’Content-Type’: ’text/html’ });
res.end(‘
<h1>Welcome to My Node App</h1>
<p>Current server time: ${getCurrentTime()}</p>
‘);
} else if (url === ’/about’) {
res.writeHead(200, { ’Content-Type’: ’text/html’ });
res.end(’<h1>About Page</h1><p>This is a simple Node.js server.</p>’);
} else if (url === ’/data’) {
fs.readFile(path.join(__dirname, ’data.json’), ’utf8’, (err, data) => {
if (err) {
res.writeHead(500, { ’Content-Type’: ’application/json’ });
res.end(JSON.stringify({ error: ’Failed to load data.’ }));
return;
}
res.writeHead(200, { ’Content-Type’: ’application/json’ });
res.end(data);
});
} else {
res.writeHead(404, { ’Content-Type’: ’text/html’ });
res.end(’<h1>404 - Page Not Found</h1>’);
}
});
server.listen(PORT, () => {
console.log(‘Server running at http://localhost:${PORT}‘);
});
| Concept | Explanation |
| -------------- | ----------------------------------------------- |
| ‘http‘ module | Used to create a web server. |
| ‘fs‘ module | Reads a local file (‘data.json‘). |
| Routing | Handles different URLs: ‘/‘, ‘/about‘, ‘/data‘. |
| Modularization | Imports ‘getCurrentTime‘ from ‘utils.js‘. |
| JSON handling | Serves JSON data via ‘/data‘ route. |
| Error handling | Simple handling for missing file. |