I am developing an NPM package. Now I want to know the easiest way to get the root of the project which utilizes my custom package.
我正在开发一个NPM包。现在我想知道获取利用我的自定义包的项目的根的最简单方法。
Within my package itself it is pretty easy to get the root in node.js like so:
在我的包本身内,很容易在node.js中获取root,如下所示:
__dirname
This points to the root of my package itself though. I would like to get the root of the project which actually performed the npm install
of my package though.
这指向了我的包本身的根。我想获得实际执行我的包的npm安装的项目的根目录。
Obviously, I could simply go up from the node_modules
directory and assume that the root directory is there but this sounds really bad.
显然,我可以简单地从node_modules目录上去,并假设根目录在那里,但这听起来很糟糕。
Is there a standard way to achieve this?
有没有一种标准的方法来实现这一目标?
2 个解决方案
#1
1
You can use the info from: require.main
您可以使用以下信息:require.main
The Module object representing the entry script loaded when the Node.js process launched. See "Accessing the main module".
Module对象,表示Node.js进程启动时加载的条目脚本。请参阅“访问主模块”。
const path = require('path');
console.log(path.dirname(require.main.filename));
Having this folder structure:
有这个文件夹结构:
/app
entry.js
node_modules/
my-package/
index.js
app/entry.js
应用程序/ entry.js
const myPackage = require('my-package');
app/node_modules/my-package/index.js
应用程序/ node_modules /我的包/ index.js
const path = require('path');
console.log(path.dirname(require.main.filename));
And when you call: node entry.js
当你调用:node entry.js
You will get: /app
printed to stdout.
你会得到:/ app打印到stdout。
#2
0
you could use app-root-path which is an npm module and its pretty neat.
你可以使用app-root-path这是一个npm模块,它非常整洁。
npm i -S app-root-path
npm i -S app-root-path
after that just do
之后就这样做了
var reqlib = require('app-root-path').require;
var myModule = reqlib('/lib/my-module.js');
#1
1
You can use the info from: require.main
您可以使用以下信息:require.main
The Module object representing the entry script loaded when the Node.js process launched. See "Accessing the main module".
Module对象,表示Node.js进程启动时加载的条目脚本。请参阅“访问主模块”。
const path = require('path');
console.log(path.dirname(require.main.filename));
Having this folder structure:
有这个文件夹结构:
/app
entry.js
node_modules/
my-package/
index.js
app/entry.js
应用程序/ entry.js
const myPackage = require('my-package');
app/node_modules/my-package/index.js
应用程序/ node_modules /我的包/ index.js
const path = require('path');
console.log(path.dirname(require.main.filename));
And when you call: node entry.js
当你调用:node entry.js
You will get: /app
printed to stdout.
你会得到:/ app打印到stdout。
#2
0
you could use app-root-path which is an npm module and its pretty neat.
你可以使用app-root-path这是一个npm模块,它非常整洁。
npm i -S app-root-path
npm i -S app-root-path
after that just do
之后就这样做了
var reqlib = require('app-root-path').require;
var myModule = reqlib('/lib/my-module.js');