Get application full path in Node.js

后端 未结 2 1145
南笙
南笙 2021-02-13 20:24

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/m

相关标签:
2条回答
  • 2021-02-13 21:11

    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)
    
    0 讨论(0)
  • 2021-02-13 21:19

    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
    
    0 讨论(0)
提交回复
热议问题