[node.js] res.sendFile absolute path

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.

This question is related to node.js express path

The answer is


If you want to set this up once and use it everywhere, just configure your own middleware. When you are setting up your app, use the following to define a new function on the response object:

app.use((req, res, next) => {
  res.show = (name) => {
    res.sendFile(`/public/${name}`, {root: __dirname});
  };
  next();
});

Then use it as follows:

app.get('/demo', (req, res) => {
  res.show("index1.html");
});

res.sendFile( __dirname + "/public/" + "index1.html" );

where __dirname will manage the name of the directory that the currently executing script ( server.js ) resides in.


Another way to do this by writing less code.

app.use(express.static('public'));

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

you can use send instead of sendFile so you wont face with error! this works will help you!

fs.readFile('public/index1.html',(err,data)=>{
if(err){
  consol.log(err);
}else {
res.setHeader('Content-Type', 'application/pdf');

for telling browser that your response is type of PDF

res.setHeader('Content-Disposition', 'attachment; filename='your_file_name_for_client.pdf');

if you want that file open immediately on the same page after user download it.write 'inline' instead attachment in above code.

res.send(data)

I tried this and it worked.

app.get('/', function (req, res) {
    res.sendFile('public/index.html', { root: __dirname });
});

process.cwd() returns the absolute path of your project.

Then :

res.sendFile( `${process.cwd()}/public/index1.html` );

Based on the other answers, this is a simple example of how to accomplish the most common requirement:

const app = express()
app.use(express.static('public')) // relative path of client-side code
app.get('*', function(req, res) {
    res.sendFile('index.html', { root: __dirname })
})
app.listen(process.env.PORT)

This also doubles as a simple way to respond with index.html on every request, because I'm using a star * to catch all files that weren't found in your static (public) directory; which is the most common use case for web-apps. Change to / to return the index only in the root path.


I use Node.Js and had the same problem... I solved just adding a '/' in the beggining of every script and link to an css static file.

Before:

<link rel="stylesheet" href="assets/css/bootstrap/bootstrap.min.css">

After:

<link rel="stylesheet" href="/assets/css/bootstrap/bootstrap.min.css">

Just try this instead:

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

This worked for me. the root:__dirname will take the address where server.js is in the above example and then to get to the index1.html ( in this case) the returned path is to get to the directory where public folder is.


An alternative that hasn't been listed yet that worked for me is simply using path.resolve with either separate strings or just one with the whole path:

// comma separated
app.get('/', function(req, res) {
    res.sendFile( path.resolve('src', 'app', 'index.html') );
});

Or

// just one string with the path
app.get('/', function(req, res) {
    res.sendFile( path.resolve('src/app/index.html') );
});

(Node v6.10.0)

Idea sourced from https://stackoverflow.com/a/14594282/6189078


Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to express

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block jwt check if token expired Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] npm notice created a lockfile as package-lock.json. You should commit this file Make Axios send cookies in its requests automatically What does body-parser do with express? SyntaxError: Unexpected token function - Async Await Nodejs Route.get() requires callback functions but got a "object Undefined" How to redirect to another page in node.js

Examples related to path

Get Path from another app (WhatsApp) How to serve up images in Angular2? How to create multiple output paths in Webpack config Setting the correct PATH for Eclipse How to change the Jupyter start-up folder Setting up enviromental variables in Windows 10 to use java and javac How do I edit $PATH (.bash_profile) on OSX? Can't find SDK folder inside Android studio path, and SDK manager not opening Get the directory from a file path in java (android) Graphviz's executables are not found (Python 3.4)