Node: TypeError – path must be absolute

Node Errors:

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

Solution:

The error states that you need to specify an absolute path instead of relative path.

There are two approach to solve this:
Approach 1:
dirname+index file
– assuming that index.html is in the same directory as the script

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

Approach 2:
– specify the root which is used as the base path for the first argument to res.sendFile()

res.sendFile(‘index.html’,{root: __dirname});

Considering the best approach is specifying the root path. When passing the user-generated file path which could possibly contain malformed or malicious parts such as ../../../etc/mms.
Setting the root path will prevent path from being access outside the base path.

In the extreme case if you trust the path then path.resolve will be an option

var path = require('path');

// All other routes should redirect to the index.html
 app.route('/*')
 .get(function(req, res) {
 res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
 });


Learn about Nodejs: