Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Express Basics (2015) Serving Static Files in Express Setting Up the Express Static Server in Development

Confused why we use __dirname

I'm confused why we use __dirname + '/public' or the same format for templates.

I can see that __dirname contains the path to the current file, but if that file isn't the src/ directory, wouldn't the path still be incorrect? It seems like it will break just as easily as something like ./public, since it's not root-relative.

I feel like I'm not quite understanding the purpose of __dirname, unless it's simply a best practice instead of using ./directory-name

Can anyone shed light on this?

Colin Marshall
Colin Marshall
32,861 Points

I was a little confused by this myself. Huston Hedinger could you please explain? Thanks!

4 Answers

Bobby Verlaan
Bobby Verlaan
29,461 Points

Hi tim,

Interesting question! I found an answer on stackoverflow that explains the difference between the two methods you propose: http://stackoverflow.com/questions/8131344/what-is-the-difference-between-dirname-and-in-node-js

It states: . gives you the directory from which you ran the node command in your terminal window (i.e. your working directory).

Depending on the location from which you start your node server the . method will give you a different path.
So from what I understand __dirname is less prone to errors.

Hope this answers your question!

Best, Bobby

Colin Marshall
Colin Marshall
32,861 Points

That makes perfect sense, thank you!

I just built a Node app using Express Generator and with that you run the node command on /bin/www instead of on app.js. So without __dirname the paths would all have to start with: ./../ to get back to the root directory of the app.

I know you've figured it out by now, but if you're curious, you can do something like this and get the directory name for a js file:

var path = require('path');
console.log(`This file is at ${path.basename(__dirname)}`);

When I did this, it helped put __dirname in context. (Those are backtics in console.log, not single quotes.)

I think, ' __dirname' is a "dynamic path", a circumstantial path name that denotes the directory from where we start the node app

Thanks, Bobby! That helps a ton.