const http = require('http');
const fs = require('fs');
const path = require('path');
// Create an HTTP server
const server = http.createServer((req, res) => {
// Set response headers
res.writeHead(200, {
'Content-Type': 'text/plain',
'Transfer-Encoding': 'chunked' // Enable chunked transfer encoding
});
// Write the response in chunks
const chunks = [
'This is the first chunk of data.\n',
'This is the second chunk of data.\n',
'This is the third and final chunk of data.\n'
];
let index = 0;
// Function to send chunks with delay
function sendChunk() {
if (index < chunks.length) {
// Write a chunk of data
res.write(chunks[index]);
console.log(`Sent chunk ${index + 1} of ${chunks.length}`);
index++;
// Schedule next chunk
setTimeout(sendChunk, 1000);
} else {
// End the response
res.end('\nAll chunks have been sent.\n');
console.log('Finished sending all chunks');
}
}
// Start sending chunks
console.log('Starting to stream response...');
sendChunk();
});
// Start the server
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
console.log(`Try: curl http://localhost:${PORT}/`);
console.log('Or open the URL in a web browser');
});
// Handle server errors
server.on('error', (err) => {
console.error('Server error:', err);
});
// Handle client connection errors
server.on('clientError', (err, socket) => {
console.error('Client error:', err);
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
// Handle process termination
process.on('SIGINT', () => {
console.log('\nShutting down server...');
server.close(() => {
console.log('Server has been shut down');
process.exit(0);
});
});