App base path from a module in NodeJS

72,394

Solution 1

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 application from the base application directory. However, if you execute your node application from different directory, say, its parent directory (e.g. node yourapp\index.js) then __dirname mechanism will work much better.

I hope that will help.

Solution 2

You can use path.resolve() without arguments to get the working directory which is usually the base app path. If the argument is 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 app root.

Solution 3

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

global.__basedir = __dirname;

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

var base_path = __basedir
Share:
72,394
Clint Powell
Author by

Clint Powell

Updated on April 03, 2020

Comments

  • Clint Powell
    Clint Powell about 4 years

    I'm building a web app in NodeJS, 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 app 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 under Windows so there is no process.env.PWD and I don't want to be platform specific anyway.

  • Clint Powell
    Clint Powell over 10 years
    process.cwd() works great with the app running at the app base path. Thanks! The ../../ works, but it feels more hacked together.
  • Neithan Max
    Neithan Max over 4 years
    What I don't like about this one is that I lose autocompletion :(
  • teoring
    teoring over 2 years
    I see people don't recommend to use global variables generally.