Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get application full path in Node.js

Tags:

node.js

I'm wondering if there is a best way or best practice to get the full path of application in Node.js. Example: I have a a module in sub folder /apps/myapp/data/models/mymodel.js, and I would like to get the full path of the app (not full path of the file), which will return me /apps/myapp, how do I do that? I know _dirname or _file is only relative to the file itself but not the full path of the app.

like image 850
Nam Nguyen Avatar asked Sep 04 '13 17:09

Nam Nguyen


People also ask

How do I get the full path in NodeJS?

We can get the path of the present script in node. js by using __dirname and __filename module scope variables. __dirname: It returns the directory name of the current module in which the current script is located.

How do I find the base path in NodeJS?

You can use process. cwd() which returns the current working directory of the process. That command works fine if you execute your node application from the base application directory. However, if you execute your node application from different directory, say, its parent directory (e.g. node yourapp\index.

What is __ Dirname in node?

__dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file. Difference between process.cwd() vs __dirname in Node.js is as follows: process.cwd()


2 Answers

There's probably a better solution, BUT this should work:

var path = require('path');

// find the first module to be loaded
var topModule = module;

while(topModule.parent)
  topModule = topModule.parent;

var appDir = path.dirname(topModule.filename);
console.log(appDir);

EDIT: Andreas proposed a better solution in the comments:

path.dirname(require.main.filename)

EDIT: another solution by Nam Nguyen

path.dirname(process.mainModule.filename)
like image 59
Laurent Perrin Avatar answered Oct 06 '22 08:10

Laurent Perrin


This worked for me.. With supervisor running the app from a different dir.

require('path').dirname(Object.keys(require.cache)[0])

example.. files: /desktop/ya/node.js

  require('./ya2/submodule')();

/desktop/ya/ya2/submodule.js

module.exports = function(){
    console.log(require('path').dirname(Object.keys(require.cache)[0]))
}

$ node node.js  
       => /desktop/ya

$ (from /desktop) supervisor ya/node.js
       => /desktop/ya
like image 45
John Williams Avatar answered Oct 06 '22 09:10

John Williams