Question

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?

Was it helpful?

Solution

process.cwd() will provide that.

OTHER TIPS

__dirname gives you the path where a file resides.

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.

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
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top