Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221402

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?

Upvotes: 19

Views: 3630

Answers (5)

Casper Beyer
Casper Beyer

Reputation: 2301

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.

Upvotes: 9

Trojan
Trojan

Reputation: 1456

In simple lines, u can call your own folder as module :

For that we need: global and app-module-path module

here "App-module-path" is the module ,it enables you to add additional directories to the Node.js module search path And "global" is, anything that you attach to this object will b available everywhere in your app.

Now take a look at this snippet:

global.appBasePath = __dirname;

require('app-module-path').addPath(appBasePath);

__dirname is current running directory of node.You can give your own path here to search the path for module.

Upvotes: 1

Marcs
Marcs

Reputation: 3838

A symlink with npm link

To avoid problems or modify source code I would use npm link, from your example:

First:

cd /another/dir/node_modules/foo  # go into the package directory
npm link                          # creates global link

This will create a global link for the foo module, on Linux you need root permissions to do this.

Then:

cd /some/folder/ # go into some other package directory.
npm link foo     # link-install the package

/some/folder/package.json should contain foo as a dep, is not mandatory, without it you get an extraneous warning with npm ls:

"dependencies": {
    [...]
    "foo": "*"
  }

No symlink with local NODE_PATH

You don't like symlinks ? You can still use NODE_PATH but locally instead setting a global variable as @rocketspacer suggested, because as he rightly stated, it's not recommended to use it globally.

Note: In any case I would use a User variable and not a System-wide variable, a co-worker could log with a different username on the same machine and still get a modified NODE_PATH.

But to do this locally for just one invocation on Linux you can simply call:

NODE_PATH=$NODE_PATH:/another/dir/node_modules npm start

It will use that NODE_PATH only for that invocation.

Same one time invocation on Windows:

@ECHO OFF

SET BASE_NODE_PATH=%NODE_PATH%
SET NODE_PATH=%BASE_NODE_PATH%;C:\another\dir\node_modules\
node index.js
SET NODE_PATH=%BASE_NODE_PATH%

And...

You could also use a local dep like:

"dependencies": {
  "foo": "file:/another/dir/node_modules/foo"
}

But would require an npm install and it would copy the content of foo in the current package node_modules folder.

Upvotes: 7

tu4n
tu4n

Reputation: 4460

"require(X) from module at path Y"

Means calling require(X) from within a file located at path Y. So you practically can't change Y.


Although the above solutions work (modifying module.paths & requiring absolute path), you'll have to add those snippets to every file in your project where you need requiring the foreign modules.

Even more, modifying module.paths is not officially supported. So it's not guaranteed to work in future updates of node


Introducing NODE_PATH

NODE_PATH is an environment variable that is set to a colon-delimited list of absolute paths.

Within those absolute paths, Node.js will search for a module that matches your require statement when all else has failed (Having indexed node_modules up to File System Root and still no match was found)

It is officially supported, although not recommended as it goes against convention (Your co-worker may not be aware of the NODE_PATH usage as there is no descriptive way of telling that in your project itself)

Notes:

  • On Windows, NODE_PATH is delimited by semicolons instead of colons.
  • Node doesn't look for node_modules within those paths like its default behavior, so your paths should be exactly where you contain needed modules. For example: "/another/dir/node_modules"


Detailed information can be found on NodeJs official document:
https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders

For those of you who are unaware of what environment variables is and how to set them, I have a windows screenshot that will get you started

enter image description here

Upvotes: 2

Medet Tleukabiluly
Medet Tleukabiluly

Reputation: 11940

It's quite easy to achieve, just add absolute paths to module object

in your current script /some/folder/node_modules/mine/my_module.js add this

module.paths.push('/another/dir/node_modules'); 
                   //this must be absolute, like /Users/John/another/dir/node_modules

var foo = require('foo');

For demo, open node in terminal, and type module.paths, it will show all the path node will search for require, you just add your path

Upvotes: 3

Related Questions