Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

res.sendFile absolute path

People also ask

What does res sendFile do?

The res. sendFile() function basically transfers the file at the given path and it sets the Content-Type response HTTP header field based on the filename extension.

How do I send a file in reply express?

The sendFile() Method. The Express framework provides a sendFile() method available on the response object which can be used to send static files to the client. Next, create an app. js file in the root folder of your project and add the following code to create a simple Express.

What is __ Dirname in node?

__dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file.

Is Res sendFile async?

res. sendFile() is asynchronous and it will end its own response if it is successful. So, when you call res.


The express.static middleware is separate from res.sendFile, so initializing it with an absolute path to your public directory won't do anything to res.sendFile. You need to use an absolute path directly with res.sendFile. There are two simple ways to do it:

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

Note: __dirname returns the directory that the currently executing script is in. In your case, it looks like server.js is in app/. So, to get to public, you'll need back out one level first: ../public/index1.html.

Note: path is a built-in module that needs to be required for the above code to work: var path = require('path');


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.


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

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


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