Formidable and Node.js TypeError: Cannot read property 'path' of undefined

Jamie Counsell picture Jamie Counsell · Mar 10, 2015 · Viewed 9.2k times · Source

If you're reading this, you're probably following Manuel Kiessling's Node tutorial. I was receiving the following error when completing the file upload part of the tutorial.

fs.rename(files.upload.path, "img/img.jpg", function(error) {
                              ^
TypeError: Cannot read property 'path' of undefined

I searched around, found this and this, but they were pretty inconclusive and provided little help.

Answer

Jamie Counsell picture Jamie Counsell · Mar 10, 2015

First, it is true that the tutorial is passing request and response in the wrong order. The first thing I did is changed the order from (response, request) to (request, response). (Make sure to do this everywhere). The reason for this is because I'm pretty sure the onRequest function in HTTP's createServer() passes them in this order.

Once I did that, I still got the same error. But by logging the information coming through from my form

...
var form = new formidable.IncomingForm();
console.log("About to parse...");
form.parse(request, function(error, fields, files) {

    console.log("Parsing done.");
    console.dir(request.headers);
    console.log(fields);
    console.log(files);
...

I noticed that the fields key contained what I was looking for, and the files key was empty.

{ upload: '2015-03-08 14.54.06.jpg', 'Upload File': 'Submit' }
{}

From here it's clear that I could use fields.upload. Using this returned another error that it was not a string (or at least not one that formidable would accept). toString() didn't seem to work either, so I used the alternate conversion:

fs.rename(fields.upload + "", "img/img.jpg", function(error) {
    ...
}

Which is not ideal, but it did the trick.

This was done with [email protected] and [email protected]. I don't know if my solution will work for everyone, but hopefully it can point some of you in the right direction. The discrepancy is probably due to the fact that he used older versions of node and formidable in the tutorial.