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.
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.
__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.
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:
res.sendFile(path.join(__dirname, '../public', 'index1.html'));
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 require
d 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With