res.sendFile absolute path

Kaya Toast picture Kaya Toast · Aug 23, 2014 · Viewed 286.5k times · Source

If I do a

res.sendfile('public/index1.html'); 

then I get a server console warning

express deprecated res.sendfile: Use res.sendFile instead

but it works fine on the client side.

But when I change it to

res.sendFile('public/index1.html');

I get an error

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

and index1.html is not rendered.

I am unable to figure out what the absolute path is. I have public directory at the same level as server.js. I am doing the res.sendFile from with server.js. I have also declared app.use(express.static(path.join(__dirname, 'public')));

Adding my directory structure:

/Users/sj/test/
....app/
........models/
....public/
........index1.html

What is the absolute path to be specified here ?

I'm using Express 4.x.

Answer

Mike S picture Mike S · Aug 23, 2014

The express.static middleware is separate from res.sendFile, so initializing it with an absolute path to your public directory won't do anything to res.sendFile. You need to use an absolute path directly with res.sendFile. There are two simple ways to do it:

  1. res.sendFile(path.join(__dirname, '../public', 'index1.html'));
  2. res.sendFile('index1.html', { root: path.join(__dirname, '../public') });

Note: __dirname returns the directory that the currently executing script is in. In your case, it looks like server.js is in app/. So, to get to public, you'll need back out one level first: ../public/index1.html.

Note: path is a built-in module that needs to be required for the above code to work: var path = require('path');