b11 b11 - 4 months ago 24
Javascript Question

How to use _dirname with a sibling directory

My directory is set up like this:


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
and not

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

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


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.