Is it possible to make the node command see a node_modules folder on a different location than the specified one?

Viewed 88

I know I can install Node.js libraries with the command npm from the command line... So, if I type:

npm install mylibrary

It'll create a node_modules folder on my current location and it'll install mylibrary (if it exists on npm)... Let's say that I create a Node.js code using it as the following:

const mylibrary = require('mylibrary')
mylibrary.doSomething()

Since I've installed this library on my current folder with the last command, this node.js script will work only if I save it on a file on my terminal current location as well. If I name this file as file.js, I can execute it with:

node file.js

Well, my problem is that I have a very specific case where the node_modules folder cannot exist in the same location that my file.js. Also, I'd like to avoid having to install mylibrary globally. Is there any way of defining as a parameter the path that the command node will search for the node_modules folder? I've checked node --help and it seems there's a lot of options, but I didn't manage to make it work. Is it possible to do? Can I use a node_modules folder that's neither the one of my file.js path or a global installed library?

1 Answers

You can have a link for the node_modules folder. For example, to create the symbolink link in Linux do this:

cd /path/to/script/folder
ln -s /path/to/where/you/can/have/node_modules node_modules

If you can't have the link, use the full path to the node_modules folder in the require, for example:

const mylibrary = require('/path/to/node_modules/mylibrary')

Also, you can solve the problem by using the NODE_PATH environment variable, set it like this

export NODE_PATH=/path/to/node_modules
Related