404 error when using response.sendfile in Express.js


I have an Express Node.js application. The structure is the following:

  +-- node_modules
  +-- public
         |-- htmls
               |-- myhtml.html
  +-- routes
         |-- index.js
  |-- app.js

My app.js is as follows:

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

// all environments
// some stuff...
app.use(express.static(path.join(__dirname, 'public')));
app.use('/public', express.static(path.join(__dirname, 'public')));

app.get('/', routes.index);
app.get('/content/:file', routes.plainhtml);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));

My routes/index.js is as follows:

// Some stuff...
exports.plainhtml = function(req, res) {
  res.sendfile('/public/htmls/' + req.params.file);

I open my browser and try to get the following address: http://localhost:3000/content/myhtml.html and I get 404 error:

Express 404 Error: ENOENT, stat '/public/htmls/myhtml.html'

The routing is done and the function is called... the problem is when I try to use res.sendfile. What address should I pass there???

What to do?

Problem courtesy of: Andry


Your express app is in app.js.

The path parameter for sendfile is a relative path. So when you do res.sendfile('xxx.js'), express will look for xxx.js in the same directory that app.js is in.

If path starts with a slash / it means that it's an absolute path in the file system e.g. /tmp.

If you are using relative paths you can also specify the root path:

res.sendfile('passwd', { root: '/etc/' });

See the docs.

Solution courtesy of: mak


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.