Merc
Merc

Reputation: 17087

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:

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.

Upvotes: 5

Views: 1824

Answers (1)

mscdex
mscdex

Reputation: 106736

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.

Upvotes: 8

Related Questions