3

I have a question regarding the Formidable Module in Npm. Im using it to parse the incoming File from my Fileupload Frontend, and then save it locally using fs.rename. This already works, so far so good. I would now like to introduce a form of error Handling if the rename fails, but for some reason it tells me that I have a unhanded error (even though it is handled).

app.post('/upload/:id', function(req, res) {

var type = req.query.type;
console.log(type);
var clubId = req.params.id;
var fileName = clubId.toString();
console.log(clubId);


var form = new formidable.IncomingForm();
form.uploadDir = baseUrl + "indesign_test/sticker_pdfs/" + clubId;
form.on('file', function(field, file) {
    var originalName = file.name;
    if (originalName.indexOf('.pdf') >= 0 && type == '.pdf') {
        fs.rename(file.path, path.join(form.uploadDir, fileName + '.pdf', function(err) {
          if (err) console.log('Test Error: ' + err.code);  // <- Error Handling here
      });
    } else {
        console.log('Error Wrong Format, expected upload in Format of' + type);
    }

});
form.on('error', function(err) {
    console.log('An error has occured: \n' + err);
});
form.on('end', function() {
    res.end('success');
});

form.parse(req);
})

Instead I get this unhanded Error:

 events.js:182
  throw er; // Unhandled 'error' event
  ^

Error: ENOENT: no such file or directory, open '/Users/stickerstars-it-mbp/Desktop/indesign_test/sticker_pdfs/339/upload_be8ff3bd80f5cb2bf1658493157e459f'
stickertmbpsMBP:node-fileupload stickerstars-it-mbp$ 
4
  • Schmotz Did you ever figure this out? Commented Sep 20, 2017 at 15:36
  • Yes, instead of saving the local upload path on the 'form.uploadDir' use a regular variable instead. If you want I can post a full answer, but this fixed it for me Commented Sep 21, 2017 at 8:10
  • 1
    @JanSchmutz If you solved your own issue, could you please post an answer and accept it? Commented Nov 29, 2017 at 21:29
  • @Vitalii Zurian I posted an answer hope this helps Commented Nov 30, 2017 at 15:01

1 Answer 1

1

For some reason you can't save the upload-path on the form.uploadDir Object. Use a regular variable instead. Here's the updated code example:

var form = new formidable.IncomingForm();
//upload path on variable instead the form object
var uploadPath = baseUrl + "indesign_test/sticker_pdfs/" + clubId;

form.on('file', function(field, file) {
    var originalName = file.name;
    if (originalName.indexOf('.pdf') >= 0 && type == '.pdf') {
        fs.rename(file.path, path.join(uploadPath, fileName + '.pdf', function(err) {
          if (err) console.log('Test Error: ' + err.code);  
      });
    } else {
        console.log('Error Wrong Format, expected upload in Format of' + type);
    }

});

In this example the error handling works without problems

Not the answer you're looking for? Browse other questions tagged or ask your own question.