简体   繁体   中英

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. 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') .
  • Put the module in node_modules/sqrt/index.js and then do a require('sqrt') .

I just want to be able to require('common-math').sqrt just like all the consumers of this package do. 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?

Node's module loading system is very limited, but what you want is possible. 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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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