Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - res.sendFile - Error: ENOENT but the path is correct

I'm trying to render an index.html but I get the error enoent, even with the right path.

//folders tree
test/server.js
test/app/routes.js
test/public/views/index.html

//routes.js    
app.get('*', function(req, res) {
    res.sendFile('views/index.html');
});


//server.js
app.use(express.static(__dirname + '/public'));
require('./app/routes')(app);

I also tried

res.sendFile(__dirname + '/public/views/index.html');

If I use

res.sendfile('./public/views/index.html');

then it works, but I see a warning that says sendfile is deprecated and I have to use sendFile.

like image 742
Alex Avatar asked Sep 01 '25 01:09

Alex


2 Answers

Try adding :

 var path = require('path');
 var filePath = "./public/views/index.html"
 var resolvedPath = path.resolve(filePath);
 console.log(resolvedPath);
 return res.sendFile(resolvedPath);

This should clear up whether the file path is what you expect it to be

like image 67
NiallJG Avatar answered Sep 02 '25 17:09

NiallJG


Try using the root option, that did it for me :

var options = {
    root: __dirname + '/public/views/',
};

res.sendFile('index.html', options, function (err) {
    if (err) {
      console.log(err);
      res.status(err.status).end();
    }
    else {
      console.log('Sent:', fileName);
    }
  });
like image 35
xShirase Avatar answered Sep 02 '25 16:09

xShirase