如何获取安装我的 npm 模块的项目的根目录?

How to get the root of project which installed my npm module?

我正在开发一个 NPM 包。现在我想知道获取使用我的自定义包的项目根目录的最简单方法。

在我的包中,很容易在 node.js 中获取根目录,如下所示:

__dirname

虽然这指向我的包本身的根目录。不过,我想获取实际执行我的包的 npm install 的项目的根目录。

显然,我可以简单地从 node_modules 目录向上并假设根目录在那里,但这听起来很糟糕。

是否有实现此目的的标准方法?

您可以使用以下信息:require.main

The Module object representing the entry script loaded when the Node.js process launched. See "Accessing the main module".

const path = require('path');
console.log(path.dirname(require.main.filename));

具有此文件夹结构:

/app
  entry.js
  node_modules/
    my-package/
      index.js

app/entry.js

const myPackage = require('my-package');

app/node_modules/my-package/index.js

const path = require('path');
console.log(path.dirname(require.main.filename));

当你打电话时:node entry.js

您将得到:/app 打印到标准输出。

您可以使用 app-root-path,它是一个 npm 模块,非常简洁。

npm i -S app-root-path

之后就做

var reqlib = require('app-root-path').require;
var myModule = reqlib('/lib/my-module.js');

const fullPath = path.dirname(require.main.filename);
const regexResp = /^(.*?)node_modules/.exec(fullPath);
const appRoot = regexResp ? regexResp[1] : fullPath;
console.log(appRoot); // outputs the directory which is the root of this project