NPM - path to root of the application


I am developing a NPM package, which needs to require a module from the application root. Think of it as the package requiring a properties module, which is placed in the application root by the user.

How do I get the path to root of the application?


To summarize what I am trying to do, express allows you to do something like this:


The router function will get app as the parameter. The idea is to allow the users to specify the routes in a separate file, and they just need to follow certain conventions like putting their controllers in /controllers folder, and my module will be able to dynamically parse the path, and then invoke the correct method in the correct module. I have already got it working, but just realized that if I package it in NPM, I no longer have access to the path of the app, so I can't invoke a controller module's method dynamically.

Problem courtesy of: jeffreyveon


Make the user call a function that sets the variables:

  myModule = new MyModule(json)

Then the user can require their root config and init your module with it.

Update In response to edited question:

Express allows you to define routes like this:

var routes = require('./routes')

//Routes Module = function(req, res) {
  res.render('info', {title: 'Express'})

I believe this is exactly what you are trying to do. Is it not?

Update 2:

You can find the directory the currently executing script is in using __dirname

Solution courtesy of: Chris Biscardi


Try this.

var path = require('path');
Discussion courtesy of: João Rocha da Silva

I have same question.

And I can only find this environment variable help:


It would always point to the root of your application path where it running.

Discussion courtesy of: mytharcher

This recipe can be found in it's original form on Stack Over Flow.