2

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..)

1 Answer 1

1

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 :-)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.