Search code examples
node.jsbusboy

Handling a field error using busboy (prevent submission of file if there is a field error)


I'm using busboy to upload a file in the manner described in the code below. If there's a validation error in the field stage I don't want to process the file (i.e. dont want to upload the file), not sure how I can do it... because both on file and on field fire asynchronoushly

    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
      // upload file

    busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) {
      console.log('Field [' + fieldname + ']: value: ' + inspect(val));
      if (val == null) {
          res.render("error meessage on page please enter a value")
      }
    });

    busboy.on('finish', function() {
      console.log('Done parsing form!');
    });

    req.pipe(busboy);

Solution

  • var fieldError = false;
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
      // upload file
    file.on('error', function (err) {
            });
    })
    busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) {
      console.log('Field [' + fieldname + ']: value: ' + inspect(val));
      if (val == null) {
          fieldError = true;
      }
    });
    
    busboy.on('finish', function() {
      console.log('Done parsing form!');
      if(fieldError)
        res.render("error meessage on page please enter a value")
    });
    
    busboy.on('error', function (err) {
      //
    });
    
    req.pipe(busboy);
    

    Note: To make busboy robust, please add busboy.on('error') and file.on('error'). This is extra to your question.