File Upload Stream With Size Limit

Stream uploaded files to disk with size limit magic byte validation and temp directory cleanup for safe multipart handling.

JavascriptFile Upload

Code

javascriptsnippet
1 line
import fs from'node:fs';import path from'node:path';import crypto from'node:crypto';const MAGIC={png:Buffer.from([0x89,0x50,0x4e,0x47]),jpg:Buffer.from([0xff,0xd8,0xff]),gif:Buffer.from([0x47,0x49,0x46])};export async function streamUpload(stream,{maxSize=10*1024*1024,allowedTypes=['png','jpg','gif'],destDir='/tmp'}={}){const tmp=path.join(destDir,crypto.randomUUID());let size=0,header=Buffer.alloc(0);const ws=fs.createWriteStream(tmp);for await(const chunk of stream){size+=chunk.length;if(size>maxSize){ws.destroy();fs.unlinkSync(tmp);throw new Error('file too large');}if(header.length<4)header=Buffer.concat([header,chunk]);for(const[type,magic]of Object.entries(MAGIC))if(allowedTypes.includes(type)&&header.subarray(0,magic.length).equals(magic))break;ws.write(chunk);}ws.end();await new Promise(r=>ws.on('finish',r));return{path:tmp,size};}

How it works

File Upload Stream With Size Limit comes down to the function streamUpload.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. A Error is thrown unconditionally at its throw site — no input check sits in front of it.

The result comes back as an object carrying tmp.

What to watch for

  • The only import, node:fs, is part of the Node.js standard library.
  • The snippet leans on crypto — browser-only surfaces a bare Node process cannot provide.

Putting it to use

The entry-point signature is export async function streamUpload(stream,{maxSize=10*1024*1024,allowedTypes=['png','jpg','gif'],destDir='/…

Treat streamUpload as the API: import it, and ignore the supporting code.

The call returns tmp.

Interactive Tools for This Topic

FAQ

Is there any input checking?
No input check exists: the `Error` fires whenever execution reaches its line, not in response to any data shape.
Do I need to install anything before running this?
Nothing needs installing: `node:fs` ships with Node.js itself.