express

Express sendFile TypeError

Express sendFile is usually one of the first errors you’ll get when developing Express applications. The most common error you’ll run into looks something like this:

TypeError: path must be absolute or specify root to res.sendFile

Sample app with Express sendFile bug

If you npm install express and try running that code you’ll get an error like:

Express sendFile error

The problem here is that you need to do one of two things before using Express sendFile.

  1. Specify root
  2. Use an absolute path

1. Specify Root

You can pass in a root variable to the sendFile function and use the __dirname global to specify your applications root directory like this:

2. Use an absolute path

The other approach you can take is just passing in an absolute path to sendFile instead of a relative one. If you want, you can use __dirname again like this:

* Remember to add a slash before the file name like in the example above!

Jon Kuperman

Jon Kuperman is a Programmer, Teacher and Entrepreneur. He's currently blogging at Code Planet and podcasting at The Web Behind.

Leave a Reply

Your email address will not be published. Required fields are marked *