Loading

Quipoin Menu

Learn • Practice • Grow

node-js / Basic HTTP Server with File Upload
interview

Q1. How do you handle file uploads in a raw Node.js HTTP server?
Parse multipart/form-data manually, which is complex. Better to use modules like formidable or multer. With formidable:
const form = new formidable.IncomingForm(); form.parse(req, (err, fields, files) => { console.log(files.upload.path); });
. The file is saved to a temporary location. You can then move it to desired location with fs.rename.

Q2. How do you create an HTML form for file upload?
Create an HTML form with enctype="multipart/form-data":
. The form submits to your Node.js server. For single-page apps, you'd use JavaScript FormData and AJAX.

Q3. How do you save uploaded files to disk?
With formidable, after parsing, the file is in a temporary location. Use fs.rename or fs.copyFile to move it:
const oldPath = files.upload.filepath; const newPath = path.join(__dirname, 'uploads', files.upload.originalFilename); fs.rename(oldPath, newPath, (err) => { ... });
. Ensure the uploads directory exists first.

Q4. How do you validate uploaded files?
Check file size, type, and extension. With formidable, you can use options:
const form = formidable({ maxFileSize: 5 * 1024 * 1024, filter: ({ mimetype }) => { return mimetype && mimetype.includes('image'); } });
. Also validate on client side, but always revalidate on server for security.

Q5. How do you handle large file uploads efficiently?
Use streams to avoid loading entire file into memory. With formidable, it already streams to disk. For custom implementation, pipe the request to a write stream:
req.pipe(fs.createWriteStream('upload.txt'))
. Set appropriate limits and handle errors. Consider using cloud storage (S3) for large files in production.