Search code examples
javascriptnode.jsmodulerequire

How do I load a node module as if the current module were located somewhere else?


I have some nodejs code running in a module somewhere. From this module, I would like to load a module located in a completely different place in the file system -- for example, given the path "/another/dir" and the module name "foo", I would like Node to act as if a module running in /another/dir had called require("foo"), rather than my own module.

  My code is running here
/some/folder/node_modules/mine/my_module.js

  I have the path "/another/dir/", the string "foo",
    and want to load this module
/another/dir/node_modules/foo/index.js

In other words, the module documentation refers to the process "require(X) from module at path Y", and I would like to specify my own value for Y

Can this be accomplished? If so, how? If not, why not?


Solution

  • The simplest, is just to resolve the path into an absolute path, this will be the recommended approach for most if not all cases.

    var path = require('path');
    
    var basedir = '/another/dir';
    var filename = 'foo'; // renamed from dirname
    
    var filepath = path.join(basedir, 'node_modules', filename);
    var imports = require(filepath);
    

    If you really need to make require act as if it is in a different directory, you can push the base directory to module.paths

    module.paths.unshift('/another/dir/node_modules');
    
    var imports = require('foo');
    
    module.paths.shift();
    

    module.paths can also be modified externally via the environment variable NODE_PATH, tho that would be the least recommended approach but this does apply it globally across all modules.