Stream multipart uploads to private storage without buffering entire files, enforce size and type policy, generate server-side names, and remove incomplete artifacts.
What you will build
This tutorial produces a working, verifiable result rather than a command list. Read each command before running it, keep configuration in version control without secrets, and record the versions used for repeatable deployment.
1. Prepare the project
npm install express@5 busboy
sudo install -d -m 0750 -o "$USER" -g "$USER" ./uploads
Run preparation commands as an unprivileged application user unless a command explicitly requires sudo. A clean working tree and lockfile make rollback much easier.
2. Implement the solution
import express from 'express'; import busboy from 'busboy'; import {createWriteStream} from 'node:fs'; import {pipeline} from 'node:stream/promises'; import {randomUUID} from 'node:crypto'; import {join} from 'node:path';
const app=express();
app.post('/upload',(req,res,next)=>{const bb=busboy({headers:req.headers,limits:{files:1,fileSize:50*1024*1024}}); let task;
bb.on('file',(name,file,info)=>{if(info.mimeType!=='application/pdf'){file.resume();return;} task=pipeline(file,createWriteStream(join('uploads',`${randomUUID()}.pdf`),{flags:'wx',mode:0o600}));});
bb.on('close',async()=>{try{await task;res.status(201).json({status:'stored'});}catch(e){next(e);}}); req.pipe(bb);});
app.listen(3000);
Save the example in the filename indicated by its comment or surrounding instructions. Treat it as a minimal baseline: production applications should separate transport, business logic, persistence, and configuration into testable modules.
3. Verify end to end
node server.js
curl -i -F 'file=@document.pdf;type=application/pdf' http://127.0.0.1:3000/upload
find uploads -type f -maxdepth 1 -printf '%f %s bytesn'
Verification should cover both process state and a real request or data operation. A process that is merely running is not necessarily ready to serve traffic.
4. Troubleshooting and production notes
Client MIME types and extensions are untrusted; inspect file signatures and scan uploads before publishing. Store files outside the web root, enforce quotas, handle limit events, remove partial files, and use object storage with signed uploads when horizontal scaling.
Production checklist
- The supported Node.js LTS version and dependency lockfile are recorded.
- Configuration is validated at startup and secrets are stored outside source control.
- Input limits, authentication, authorization, timeouts, and error boundaries are explicit.
- Logs identify a request without exposing credentials or personal data.
- Health checks, graceful termination, resource limits, backup, and rollback have been tested.
Reference: official topic documentation. For production version selection, use a supported LTS line from the Node.js release schedule.