Performance: Multiple file uploads
This affects the server response time and client-side rendering speed during file upload processes.
Jump into concepts and practice - no test required
app.post('/upload', async (req, res) => { const files = req.files; await Promise.all(files.map(file => fs.promises.writeFile(`uploads/${file.name}`, file.data))); res.send('Files uploaded'); });
app.post('/upload', (req, res) => { const files = req.files; files.forEach(file => { // Synchronously save each file one by one fs.writeFileSync(`uploads/${file.name}`, file.data); }); res.send('Files uploaded'); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous file writes in upload handler | N/A | N/A | Blocks server response causing delayed client paint | [X] Bad |
| Asynchronous parallel file writes with Promise.all | N/A | N/A | Non-blocking server response enables faster client paint | [OK] Good |
single() for one file, array() for multiple files, and fields() for multiple fields.upload.array() is used.upload.array(fieldname, maxCount) accepts multiple files with the same field name and limits the count.upload.array('photos', 5) is correct.app.post('/upload', upload.array('docs', 3), (req, res) => {
res.send(req.files.length);
});upload.array('docs', 3) allows up to 3 files. If user uploads 2 files, both are accepted.req.files.length, which is the number of uploaded files, here 2.app.post('/upload', upload.array('files'), (req, res) => {
console.log(req.file);
res.send('Uploaded');
});upload.array(), uploaded files are stored in req.files (an array), not req.file.req.file, which will be undefined or incorrect for multiple files.upload.fields() with an array of objects specifying field names and max counts.upload.fields([{ name: 'images', maxCount: 3 }, { name: 'documents', maxCount: 2 }]). upload.array('images', 3), upload.array('documents', 2) is invalid syntax as you cannot chain two upload.array() calls in one route.