【问题标题】:How to get the root of project which installed my npm module?如何获取安装了我的 npm 模块的项目的根目录?
【发布时间】:2018-11-05 18:28:15
【问题描述】:

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

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

__dirname

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

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

有没有标准的方法来实现这一点?

【问题讨论】:

    标签: node.js npm npm-install node-modules


    【解决方案1】:

    您可以使用来自:require.main的信息

    Module 对象表示在 Node.js 进程启动。请参阅“访问主模块”。

    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 打印到标准输出。

    【讨论】:

    • 这给我留下了包本身的根目录,而不是使用我的包的项目的根目录。
    • 你是如何运行节点的?你是直接打电话给你的包裹吗?
    • 它在我的主项目中通过 npm 脚本作为可执行文件调用。在我的自定义包中,我在package.json 中设置了一个bin 属性。
    • 刚刚添加:path.dirname(require.main.filename) 到我在node_modules 中的任何包中,它正在打印我的项目根目录。
    • 它不可能不工作,你做错了什么,require.main.filename包含入口点,除非你的入口点不在你的项目的根目录中,你有东西别的继续。发布您的目录结构以及您的入口点在哪里。
    【解决方案2】:

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

    npm i -S app-root-path

    之后就做吧

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

    【讨论】:

    • @Stephan-v 就像你想象的那样工作,只需找到根node_modules 目录。
    【解决方案3】:

    亲吻

    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
    

    【讨论】:

      猜你喜欢
      • 2013-03-10
      • 2015-02-26
      • 2012-12-11
      • 2017-11-24
      • 1970-01-01
      • 1970-01-01
      • 2015-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多