const http = require('http');
const fs = require('fs');
const path = require('path');
// Create a server to handle file uploads
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/upload') {
// Create a write stream to a file
const filePath = path.join(__dirname, 'uploaded-file.txt');
const fileStream = fs.createWriteStream(filePath);
// Pipe the request body directly to the file
req.pipe(fileStream);
// Handle completion
fileStream.on('finish', () => {
// Get file stats to check size
fs.stat(filePath, (err, stats) => {
if (err) {
console.error('Error getting file stats:', err);
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('Error processing upload');
return;
}
// Send response
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify({
success: true,
message: 'File uploaded successfully',
size: stats.size,
path: filePath
}));
console.log(`File uploaded to ${filePath}`);
console.log(`File size: ${stats.size} bytes`);
// Clean up the file after a delay
setTimeout(() => {
fs.unlink(filePath, (err) => {
if (err) console.error('Error removing uploaded file:', err);
else console.log('Uploaded file removed');
});
}, 5000);
});
});
// Handle errors
fileStream.on('error', (err) => {
console.error('File write error:', err);
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end('Error saving file');
});
req.on('error', (err) => {
console.error('Request error:', err);
fileStream.destroy(err);
});
}
else if (req.method === 'GET' && req.url === '/') {
// Provide a simple HTML form for uploading
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(`
File Upload Example
Upload a Text File
Note: This is a simple example. A real implementation would need to parse multipart form data.
`);
}
else {
// Handle all other requests
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not Found');
}
});
// Start server
const PORT = 8080;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
// Make a test upload
setTimeout(() => {
const req = http.request({
hostname: 'localhost',
port: PORT,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'text/plain'
}
}, (res) => {
let data = '';
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => {
console.log('Upload response:', data);
});
});
req.on('error', (e) => {
console.error('Test request error:', e.message);
});
// Write some content to upload
req.write('This is a test file content uploaded using http.request.\n');
req.write('It demonstrates streaming data to the server.\n');
req.end();
}, 1000);
});
Server running at http://localhost:8080/ File uploaded to /path/to/uploaded-file.txt File size: 1234 bytes Upload response: {"success":true,"message":"File uploaded successfully","size":1234,"path":"/path/to/uploaded-file.txt"} Uploaded file removed