【问题标题】:How to require a file relative to requirer?如何要求相对于要求者的文件?
【发布时间】:2017-07-20 04:41:15
【问题描述】:

我正在开发一个库,我想加载一个或多个与要求程序相关的文件。为了更好地说明这一点:

// ~/app.js
import { horn } from 'unicorn'
horn.load()

// ~/node_modules/unicorn/horn.js
export default {
  load() {
    require('./user.config.js') // Here I would like to load the user config
                                // relative to "~/app.js"
  }
}

我尝试检查全局 require 及其 parent 属性,但它只给了我一个文件名而没有更多上下文。

【问题讨论】:

    标签: node.js configuration configuration-files


    【解决方案1】:

    以下是您可以使用的:

    module.parent
    

    这是加载此模块的第一个模块的模块句柄。因为模块句柄是缓存的,所以这只会反映加载您的第一个模块。

    module.filename
    

    这是模块的完全限定文件名。所以,如果你想要父模块的完全限定文件名,你可以使用这个:

    module.parent.filename
    

    如果您只想要父模块的路径以便可以从该目录加载某些内容,那么您可以从文件名中分离出路径,以便使用 path 模块获取路径。

    path.dirname(module.parent.filename)
    

    如果你想从那个目录加载一个文件,你可以这样做:

    let fileToLoad = path.join(path.dirname(module.parent.filename), "user.config.js");
    let config = require(fileToLoad);
    

    您必须记住上面的警告,module.parent 只返回第一个加载您的模块,因为之后该模块被缓存并且只返回原始模块句柄(它不会重新加载)。

    【讨论】:

    • 太棒了!感谢您的详细信息和建议。有时间我会试一试,然后我会回来接受答案。
    • @RubensMariuzzo - 你能试试这个吗?它对你有用吗?标记最佳答案以向社区表明问题现已完成是否合适?
    • 我还没有检查,但我会的。我已经被其他东西吸引住了。对不起!
    猜你喜欢
    • 2017-03-03
    • 2016-10-02
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多