node.js how to manage two third-party packages

Viewed 69

I'm write a node.js application. this application depend on another package, assume AAA.. so in "dependencies" of package.json should include it (above AAA)

my problem is: i want to check if user has installed AAA and use it, otherwise use AAA which my application install.

pseudolanguage:

import AAA as myAAA from 'AAA';

let fallback
if (user has been installed AAA){
  fallback = AAA;
} else {
  fallback = myAAA;
}

can i do that?

1 Answers

In short, no, what you are trying to do can not be done in a simple manner. The order by which Node.js tries to locate a module referred by name is as follows :

  1. Check to see if the given module is a core module.
  2. Search for a directory named node_modules in the current directory (project directory).
  3. Work the way up the folder hierarchy, checking each level for a node_modules folder.
  4. Look at the directory paths outlined in the require.paths array in node.

You cant make Node.JS change the order of this lookup - which is what you are trying to do.

There can be other ways to achieve this - for example, look for the global node_modules install location and see if the package is in that folder - if so, you can require() the absolute path to the global package, if not, you can require() the package as usual, and the local package will be used.

Reference:

http://www.bennadel.com/blog/2169-where-does-node-js-and-require-look-for-modules.htm

Related