2

My file structure:

- simulated-selves
  - client
    - index.html
  - server
    - app.js

I'm trying to send the user index.html when they hit the / route.

// server/app.js

app.get('/', function(req, res) {
  res.sendFile(__dirname + '/../client/index.html', null, function(err) {
    if (err) {
      console.log('error: ', err);
      res.status(err.status).end();
    }
    else res.status(200).end();
  });
});

It's not working though. This is the error that gets logged out:

error:  { [Error: Forbidden] status: 403 }

So basically I have access to __dirname in app.js. Since app.js is in the server folder, __dirname resolves to /Users/azerner/code/simulated-selves/server. Since I need to access index.html in the client folder, I need to manipulate this __dirname that I have. I know I could do some string manipulation, but I'm looking for the best way to do this.

2
  • 2
    Shouldn't it be /../client/index.html ? Commented Jul 18, 2015 at 21:21
  • Yes, it should be /../client/index.html! It's still giving me the same error though. And yes - I've restarted my server. Commented Jul 18, 2015 at 21:25

1 Answer 1

1

There is a node build-in module that deals with resolving path, which might help you with this issue

The function path.resolve will deal with the relative part (/../) and build an absolute path for you.

For example:

var path = require('path');
var clientFile = path.resolve(__dirname + '/../client/index.html');

See more info on the documentation on path http://devdocs.io/node/path#path_path_resolve_from_to

Sign up to request clarification or add additional context in comments.

3 Comments

path.resolve(__dirname, '/../client/index.html') didn't work, but path.resolve(__dirname + '/../client/index.html') did.
excellent, i wonder why passing each as arguments didnt work.
Idk, the documentation was hard for me to understand. Could you update your answer please?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.