简体   繁体   English

要求使用规范或根相对路径的NodeJS中的文件

[英]Require a file in NodeJS using a canonical or root-relative path

I have a fictional utilities package (node module) that I'm importing into my apps like so: 我有一个虚构的实用程序包(节点模块),我将其导入到我的应用程序中,如下所示:

var sqrt = require('common-math').sqrt

However, using this same module from within the common-math module seems to be tricky. 但是,在common-math模块中使用同一模块似乎很棘手。 I seem to only have to options, both of which are not ideal: 我似乎只需要选择,两者都不理想:

  • Use relative path require from every single place I need to get access to the module. 从我需要访问模块的每个地方使用相对路径要求。 This can be require('../sqrt') or require('../../../lib/sqrt') . 这可以是require('../sqrt')require('../../../lib/sqrt')
  • Put the module in node_modules/sqrt/index.js and then do a require('sqrt') . 将模块放入node_modules/sqrt/index.js ,然后执行require('sqrt')

I just want to be able to require('common-math').sqrt just like all the consumers of this package do. 我只希望能够像这个包的所有使用者一样require('common-math').sqrt I realize that I can create a node_modules/common-math folder with a symlink to my package's index.js , but is this a common/recommended practice? 我意识到我可以使用指向我包的index.js的符号链接创建一个node_modules/common-math文件夹,但这是常见/推荐的做法吗?

Node's module loading system is very limited, but what you want is possible. Node的模块加载系统非常有限,但是您想要的是可能的。 However it is not as elegant as you might expect it to be: 但是,它并不像您期望的那样优雅:

var root = (function (p, path) {
        for (; 'common-math' !== path.basename(p); p = path.dirname(p));
        return p;
    }(module.filename, require('path'));

var a = require(root + '/sqrt.js');

or even: 甚至:

var root = (function (p) {
        return p.slice(0, p.indexOf('common-math') + 1).join('/');
    }(module.filename.split('/')));

var a = require(root + '/sqrt.js');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM