Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

312
Views
How to close Busboy connection and send back an error response in ExpressJS

I have busboy in my ExpressJS app for file streaming. Now at some point I wish to send back a regular response that the file size is too large. How can I do that?

Here is my code to illustrate what I want:

     busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
          
     console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
          
           let fileSize = 0;

           file.on('data', function(data) {
           fileSize += data.length;
            console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
           });

           file.on('end', function() {
           console.log('File [' + fieldname + '] Finished');
           if (fileSize > MAXIMUM_ALLOWED_FILE_UPLOAD_SIZE) {
            //I wish to send back a regular response that the file size is too large here.
            }
           fileSize = 0;

          });
        });

        busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
          console.log('Field [' + fieldname + ']: value: ' + inspect(val));
        });

How can I achieve that?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Busboy has a maximum file byte size that you can specify in the limits option which will prevent it from pushing any more data into the file than your specified limit. If you want to limit your file upload size, I'd go with that. It emits a 'limit' event on the file if it reaches the maximum size.

Busboy also handles multiple uploads-- not sure if you wanted to handle that or not. But here's a sample with a limit and multiple uploads:

var express = require('express');
var Busboy = require('busboy');
var html_escaper = require('html-escaper');
var fs = require('fs');

var escaper = html_escaper.escape;

const MAX_UPLOAD_SIZE = 10000;

var app = express();

app.get('/', function(req, res) {
    res.writeHead(200, {'Content-type': 'text/html'})
    res.write('<!doctype html><html><body>');
    res.write('<form action="fileupload" method="post" enctype="multipart/form-data">')
    res.write('<input type="file" name="upload_1">')
    res.write('<input type="file" name="upload_2">');
    res.write('<input type="submit"></form>');
    res.write('</body></html>')
    return res.end();
})

app.post('/fileupload', function (req, res) {
    var busboy = new Busboy({ headers: req.headers, limits: { fileSize: MAX_UPLOAD_SIZE } });
    var fileList = [];
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype ) {
        fileInfo = {
            'fObj': file,
            'file': filename,
            'status': 'uploaded'
        }
        fileList.push(fileInfo);
        file.on('limit', function() {
            fileInfo.status = `Size over max limit (${MAX_UPLOAD_SIZE} bytes)`;
        });
        file.on('end', function() {
            if (fileInfo.fObj.truncated) {
                if (fileInfo.status === 'uploaded') {
                    // this shouldn't happen
                    console.error(`we didn't get the limit event for ${fObj.file}???`);
                    fileInfo.status = `Size over max limit (${MAX_UPLOAD_SIZE} bytes)`;
                }
            }
        });
        file.pipe(fs.createWriteStream(`./uploads/${fileList.length}.bin`));
    });
    busboy.on('finish', function() {
        var out = "";
        fileList.forEach(o => {
            out += `<li>${escape(o['file'])} : ${o['status']}</li>`
        });
        res.writeHead(200, {'Connection': 'close'});
        res.end(`<html><body><ul>${out}</ul></body></html>`);
    })
    return req.pipe(busboy);
});

app.listen(8080);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!