43

I'm building a web application in Node.js, and I'm implementing my API routes in separate modules. In one of my routes I'm doing some file manipulation and I need to know the base app path. If I use __dirname, it gives me the directory that houses my module of course.

I'm currently using this to get the base application path (given that I know the relative path to the module from base path):

path.join(__dirname, "../../", myfilename)

Is there a better way than using ../../? I'm running Node.js under Windows, so there isn't any process.env.PWD, and I don't want to be platform-specific anyway.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Clint Powell
  • 2,368
  • 2
  • 16
  • 19
  • Using the line above multiple times/in multiple modules is repetitive and inconsistent. It might be useful to create a _static_ function in a _static_ class (for example `Paths.getBasePath();`) in that case. You'll only need to update the relative path in the function mentioned above when your project structure changes. With an approach like this, you can use `require('./Paths').getBasePath();` anywhere, without the need to use `../../` again. – Tim Visée Aug 07 '16 at 15:53

3 Answers3

44

The approach of using __dirname is the most reliable one. It will always give you correct directory. You do not have to worry about ../../ in Windows environment as path.join() will take care of that.

There is an alternative solution though. You can use process.cwd() which returns the current working directory of the process. That command works fine if you execute your Node.js application from the base application directory. However, if you execute your Node.js application from different directory, say, its parent directory (e.g., node yourapp\index.js) then the __dirname mechanism will work much better.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tom
  • 26,212
  • 21
  • 100
  • 111
  • 1
    `process.cwd()` works great with the app running at the app base path. Thanks! The `../../` works, but it feels more hacked together. – Clint Powell Feb 07 '14 at 21:01
10

You can define a global variable like in your app.js file:

global.__basedir = __dirname;

Then you can use this global variable anywhere. Like this:

var base_path = __basedir
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hayreddin Tüzel
  • 939
  • 2
  • 9
  • 22
9

You can use path.resolve() without arguments to get the working directory which is usually the base application path. If the argument is a relative path then it's assumed to be relative to the current working directory, so you can write

require(path.resolve(myfilename));

to require your module at the application root.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Samuli Asmala
  • 1,755
  • 18
  • 24