Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a specific file from a module in node

I wrote a module, simpledblayer-mongo. The module depends on simpledblayer (it provides the DB-specific functions).

I am having a problem with unit testing. The problem here is that:

  • simpledblayer-mongo gets the list of tests from simpledblayer (the test.js file)
  • using GIT it's easy to define a "submodule" in simpledblayer-mongo and make sure that the submodule is placed under node_modules. So, the file with all the tests will be in node_modules/simpledblayer/tests
  • With NPM, I define simpledblayer as a devDependency. No real need, since simpledblayer IS needed by simpledblayer-mongo regardless, as a straight dependency

The problem I am having is this: a user might get the module from GIT (the module will guaranteed to be in node_modules/simpledblayer) or NPM (the module might be placed either in node_modules, or it might actually be deduped/etc. and it might be anywhere, really).

I need to load simpledblayer's test.js file regardless if where it is (as long as simpledblayer itself is require-able as a module). Any hint on getting a specific file from a module, regardless of what the module's path is?

Thanks!

Merc.

like image 721
Merc Avatar asked Jan 18 '15 05:01

Merc


1 Answers

You could use require.resolve() which returns an absolute path to the main property value (from the module's package.json) of the module name you pass in. From there, you can use the path/fs modules to help get to the right path, relative to the absolute path returned by require.resolve().

So if simpledblayer has main: 'index.js' in its package.json, require.resolve('simpledbplayer') might return something like /home/foo/project/node_modules/simpledblayer/index.js.

like image 118
mscdex Avatar answered Oct 01 '22 01:10

mscdex