Categories
Express JavaScript Answers

How to Call the Express res.sendFile Method with an Absolute Path?

Spread the love

To call the Express res.sendFile method with an absolute path, we can call the sendFile method with the root option set to the __dirname .

__dirname has the path string of the current working directory as its value.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

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

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

We call res.sendFile with the file path as the first argument.

It’s the path relative to the folder path set as the value of root .

root is set to __dirname , so the path in the first argument is relative to __dirname .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.