Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 964
Ryan Cavanaugh Avatar asked Nov 01 '16 18:11

Ryan Cavanaugh


People also ask

How do I load a NodeJS module?

Loading Core Modules In order to use Node. js core or NPM modules, you first need to import it using require() function as shown below. var module = require('module_name');

How do I resolve a node module error?

To fix the Cannot find module error, simply install the missing modules using npm . This will install the project's dependencies into your project so that you can use them. Sometimes, this might still not resolve it for you. In this case, you'll want to just delete your node_modules folder and lock file ( package-lock.

Where are node modules located?

On Unix systems they are normally placed in /usr/local/lib/node or /usr/local/lib/node_modules when installed globally. If you set the NODE_PATH environment variable to this path, the modules can be found by node. Non-global libraries are installed the node_modules sub folder in the folder you are currently in.


1 Answers

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.

like image 192
Casper Beyer Avatar answered Sep 28 '22 19:09

Casper Beyer