I’m developing a simple Node.js web server and I’m having some trouble handling concurrent requests. My server needs to perform the following tasks:
-
Serve a welcome message at the root URL (
/
). -
Perform a long-running computation without blocking other requests at the URL (
/long-task
). -
Read and return the contents of a file asynchronously at the URL (
/read-file
). -
Handle 404 errors for unknown routes.
Requirements:
-
The server should handle multiple requests concurrently without blocking the main thread.
-
Use asynchronous APIs provided by Node.js to achieve non-blocking I/O operations.
-
Properly handle errors and edge cases (e.g., file not found, server errors).
const fs = require('fs'); const http = require('http'); // Function to simulate a long-running task function longRunningTask(callback) { setTimeout(() => { callback('Long-running task completed'); }, 3000); // Simulate a task that takes 3 seconds } // Function to read a file asynchronously function readFileAsync(filePath, callback) { fs.readFile(filePath, 'utf8', (err, data) => { if (err) { callback(err); } else { callback(null, data); } }); } // Create an HTTP server const server = http.createServer((req, res) => { if (req.url === '/') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello, world!n'); } else if (req.url === '/long-task') { longRunningTask((message) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(message + 'n'); }); } else if (req.url === '/read-file') { readFileAsync('example.txt', (err, data) => { if (err) { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Error reading filen'); } else { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(data); } }); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Not Foundn'); } }); // Start the server server.listen(3000, () => { console.log('Server is listening on port 3000'); });
Faizan Rasheed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.