const http = require('http');
// Create an HTTP server
const server = http.createServer((req, res) => {
// req is an http.IncomingMessage, which is a ReadStream
console.log(`Received ${req.method} request to ${req.url}`);
// Set response headers
res.setHeader('Content-Type', 'text/plain');
// Handle different types of requests
if (req.method === 'GET') {
res.end('Send a POST request with a body to see the ReadStream in action');
}
else if (req.method === 'POST') {
// Set encoding for the request stream
req.setEncoding('utf8');
let body = '';
// Handle data events from the request stream
req.on('data', (chunk) => {
console.log(`Received chunk of ${chunk.length} bytes`);
body += chunk;
// Implement a simple flood protection
if (body.length > 1e6) {
// If body is too large, destroy the stream
body = '';
res.writeHead(413, {'Content-Type': 'text/plain'});
res.end('Request entity too large');
req.destroy();
}
});
// Handle the end of the request stream
req.on('end', () => {
console.log('End of request data');
try {
// Try to parse as JSON
const data = JSON.parse(body);
console.log('Parsed JSON data:', data);
// Send a response
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({
message: 'Data received',
size: body.length,
data: data
}));
} catch (e) {
// If not valid JSON, just echo back the raw data
console.log('Could not parse as JSON, treating as plain text');
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(`Received ${body.length} bytes of data:\n${body}`);
}
});
}
else {
// For other HTTP methods
res.writeHead(405, {'Content-Type': 'text/plain'});
res.end('Method not allowed');
}
});
// Start the server
const PORT = 8080;
server.listen(PORT, () => {
console.log(`HTTP ReadStream example server running at http://localhost:${PORT}`);
console.log('To test:');
console.log(`1. Open http://localhost:${PORT} in a browser for GET request`);
console.log(`2. Use curl or Postman to send POST requests with a body to http://localhost:${PORT}`);
});
// Note: To test with curl:
// curl -X POST -H "Content-Type: application/json" -d '{"name":"John","age":30}' http://localhost:8080