Reputation: 4450
I have a Node.js app ( MyGreatApp
) that requires a node module like so:
// MyGreatApp/level_1/level_2/build.js
const myNpmModule = require('myNpmModule')();
The said node module ( myNpmModule
) executes the following code:
// MyGreatApp/node_modules/myNpmModule/index.js
const path = require('path');
module.exports = function() {
console.log(path.parse(process.mainModule.filename).dir);
}
What is logged on the console is:
/Users/myname/myapps/MyGreatApp/level_1/level_2/
What I want logged on the console is:
/Users/myname/myapps/MyGreatApp/
In other words, doing path.parse(process.mainModule.filename).dir
from within a node module will return the path to the folder of the file that requires that module.
But what I want to know is the the path to the parent folder of the app that installed/uses that module.
(note: I won't know the location of the file that will be requiring myNpmModule
in advance..)
Upvotes: 2
Views: 652
Reputation: 4450
I've found an npm module that does it: app-root-path
Looks like it does all the dirty job for you only relying on __dirname
as a starting point.
If anyone has a simpler/better way please post an answer :-)
Upvotes: 1