const http = require('http');
// Create an HTTP server
const server = http.createServer((req, res) => {
// 'res' is the ServerResponse object
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
// Start the server
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
// Make a test request to the server
http.get(`http://localhost:${PORT}`, (response) => {
let data = '';
// A chunk of data has been received
response.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received
response.on('end', () => {
console.log('Response from server:', data.trim());
server.close();
});
}).on('error', (err) => {
console.error('Error making test request:', err);
server.close();
});
});
// Handle server errors
server.on('error', (err) => {
console.error('Server error:', err);
});