App base path from a module in NodeJS

99封情书 提交于 2019-12-04 22:15:41

The approach of using __dirname is the most reliable one. It will always give you correct directory. You do not have to worry about ../../ in Windows environment as path.join() will take care of that.

There is an alternative solution though. 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.js) then __dirname mechanism will work much better.

I hope that will help.

You can use path.resolve() without arguments to get the working directory which is usually the base app path. If the argument is relative path then it's assumed to be relative to the current working directory so you can write

require(path.resolve(myfilename));

to require your module at app root.

You can define a global variable like in your app.js:

global.__basedir = __dirname;

Then you can use this global variable anywhere. Like that:

var base_path = __basedir
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!