Node.js › File Uploads & Media Processing

What is the difference between multer's diskStorage and memoryStorage engines?

Beginner

Answer

diskStorage writes uploaded files directly to a specified directory on disk as they're received, returning a file path in req.file, suitable for larger files where holding the entire content in memory would be wasteful. memoryStorage keeps the uploaded file entirely in a Buffer in memory (available as req.file.buffer), convenient for smaller files that will be immediately processed or forwarded elsewhere (like directly to cloud storage) without ever needing to touch the local disk.
// Disk storage: writes to disk, file path available
const upload = multer({ storage: multer.diskStorage({ destination: 'uploads/' }) });

// Memory storage: buffer available directly, no disk write
const upload = multer({ storage: multer.memoryStorage() });
app.post('/upload', upload.single('file'), (req, res) => {
  s3.putObject({ Body: req.file.buffer, Key: req.file.originalname });
});
Real-world example An avatar-upload endpoint uses memoryStorage since uploaded images are small and immediately forwarded to S3 without ever needing a local disk copy, while a large-video-upload endpoint uses diskStorage to avoid holding potentially gigabyte-sized files entirely in memory.

Common follow-ups: What's the memory risk of using memoryStorage for an endpoint that might receive very large files?;How would you clean up temporary files left on disk by diskStorage after they've been processed?