How to prevent node.js from hanging when a big file upload is initiated? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to prevent node.js from hanging when a big file upload is initiated? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m trying to protect the app I’m working on from payload DOS attacks (when someone tries to upload a very big file). My middlewares look like this (I’m using express-fileupload and body-parser:

import fileUpload from "express-fileupload";
import { json, urlencoded } from "body-parser";

// ...

app.use(
    fileUpload({
        limits: { fileSize: 2 * 1024 * 1024 }
    })
);
app.use(json({ limit: "2mb" }));
app.use(urlencoded({ limit: "2mb", extended: true }));

My problem is that despite the fact that I configured my middlewares to limit request size to 2mb when I try to upload a 7gb file the process halts.

How do I prevent this properly?

Answer

If you want to stop the process if the size is over, use abortOnLimit option. (Otherwise, it will truncate automatically)

Like this

app.use(
    fileUpload({
        limits: { fileSize: 2 * 1024 * 1024 }
    }),
    abortOnLimit: true
);
We are here to answer your question about How to prevent node.js from hanging when a big file upload is initiated? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji