b11 b11 - 1 month ago 7
Javascript Question

How to use _dirname with a sibling directory

My directory is set up like this:

public
pages
index.html
routers
route.js


Inside route.js, I do the following:

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


I get Error: ENOENT: no such file or directory, stat because the server is looking on
myproject/routers/public/pages/index.html
and not
myproject/public/pages/index.html


1) How do I fix this issue and get it to look in the right path using
_dirname
?

2) How do I get my server to remember looking in
/public/pages/
so that I don' have to specify the absolute path every time?

Answer

So you probably want to use relative location, for your example you can do something like bellow

var html_location = './public/pages/'; //first method
var root_location = {  //second method
    root : './public/pages/'
}
router.get('/', function(req, res) {
    res.sendFile('index.html', { root : html_location}); //first method
    res.sendFile('index.html', root_location); //second method
});

so the root : '.' indicating that you will be starting the location from the folder where the main.js / app.js file is running and the file location is off from that location.

Comments