Performance: Single file upload
This affects the page load speed and interaction responsiveness when uploading files through a web form.
Jump into concepts and practice - no test required
app.post('/upload', (req, res) => { const file = req.files.file; // Asynchronously save file fs.writeFile(`./uploads/${file.name}`, file.data, (err) => { if (err) return res.status(500).send('Upload failed'); res.send('File uploaded'); }); });
app.post('/upload', (req, res) => { const file = req.files.file; // Synchronously save file fs.writeFileSync(`./uploads/${file.name}`, file.data); res.send('File uploaded'); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous file save | Minimal (file input only) | 0 | 0 | [X] Bad |
| Asynchronous file save | Minimal (file input only) | 0 | 0 | [OK] Good |
upload.single('file') do in an Express app using multer?upload.single('file') tells multer to accept one file with the field name 'file' from the form.req.file, enabling access in the route handler.const upload = multer({ dest: 'uploads/' }). Then use upload.single('avatar') in route.app.post('/upload', upload.single('avatar'), (req, res) => { ... }). app.post('/upload', upload.single('avatar'), (req, res) => { ... }) matches this.const upload = multer({ dest: 'uploads/' });
app.post('/profile', upload.single('photo'), (req, res) => {
res.send(req.file.originalname);
});
What will the server respond with after uploading a file named 'mypic.png'?req.file contains info including originalname which is the name of the file on the user's computer.req.file.originalname, so the response will be the original filename, 'mypic.png'.const upload = multer({ dest: 'uploads/' });
app.post('/upload', (req, res) => {
upload.single('file');
res.send('File uploaded');
});upload.single('file') must be passed as middleware in the route definition, not just called inside the handler.upload.single('file') is called but not used as middleware, so multer never processes the file.destination can be a string or a function with signature (req, file, cb). The filename must be a function with (req, file, cb).destination and filename, and sets filename to timestamp + original name.