This is pretty old, but here is my solution.
I needed a test conductor module, which was published in a private registry and was required for the mocha test suite. I wanted the calling test code to pass the test code to the bundle, rather than requiring it directly:
var harness = require('test-harness'); var codeUnderTest = harness('../myCode');
Inside the harness (which was found in the project directory of node_modules), I used the following code to request to find the correct file:
if (!path.isAbsolute(target)) { target = path.join(path.dirname(module.parent.paths[0]), target); } var codeUndertest = require(target); ... return codeUnderTest;
It depends on the required path resolution, which always starts with a search for the node_modules subdirectory relative to the calling file. Connect this to module.parent and you can access this search path. Then just remove the final part of node_modules and concatenate the relative file name.
For other scenarios that do not use relative paths, this can be done using the options parameter, which requires:
var codeUndertest = require(target, {paths: module.parent.paths}); ... return codeUnderTest;
And the two can also be combined. I used the first form because I actually used a proxyquire, which does not offer the paths option.
DDupont
source share