24

I have some project, and I run it with node main.js / make test etc. What I need is to get this directory from a script. Not only from main.js, but also from any submodule. I tried with path plugin and __directory, but I get a path of the current file (for example submodule). I also tried require('path').dirname(require.main.filename), but when I run make test I get mocha dirname instead of my project directory. What is the easiest way to solve this?

ciembor
  • 7,189
  • 13
  • 59
  • 100

5 Answers5

71

process.cwd() will provide that.

fiat
  • 15,501
  • 9
  • 81
  • 103
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
7

__dirname gives you the path where a file resides.

Pascal Belloncle
  • 11,184
  • 3
  • 56
  • 56
  • this and `__filename` it's file and directory of a module loaded with require not necessary executable path. – jcubic Dec 10 '20 at 09:19
1

There is also one option if you want path to executable file and not JS module. you can use:

process.argv[1] // 0 is path to node

__dirname and __filename can also be used but those are path to modules so if you put this into a file that is require it will show path to that file.

jcubic
  • 61,973
  • 54
  • 229
  • 402
0

require.cache stores every loaded module and its associated imported values, parent module, child modules, absolute file path, etc.

I believe each module is assigned to the cache object using its file path as the cache key, but you will probably want to double check that, just to make sure.

If that is the case though, something as simple as Object.keys(require.cache) will give you an array of file paths for all of the modules. Then just parse each path as needed to pull the directory information you are looking for from each module path.

0

Here is a handy function to get access to files provided with relative paths from the console

function getPath(filename) {
    return (filename[0] != '/' ? process.cwd() + '/' : "") + filename
}
Tahsin Turkoz
  • 4,356
  • 1
  • 27
  • 18