Niels
Niels

Reputation: 557

How to install a npm module in current directory?

I am trying to install express into my current "directory".
However node installs this globally and I do not understand, how I can tell node to install it in my current directory.

Upvotes: 1

Views: 4912

Answers (2)

sevenr
sevenr

Reputation: 419

I had a similar issue with installing node modules in my project directory, even when I did not specify the "-g" global flag. On Linux any packages I installed when in my current directory would end up getting installed into ~/node_modules (i.e. /home/user/node_modules).

The reason and fix are explained in the thread at npm install module in current directory. Briefly, npm looks for a node_modules subdirectory in the directory where

npm install

was invoked. If not found, npm keeps moving upwards, searching that directory's ancestors till it finds node_modules. Assuming a Linux system, if not found in the uppermost level of the current user's home, i.e. /home/user, it will create node_modules in the current dir, which is the required behaviour. However I already had a ~/node_modules directory, which did not allow this to happen.

The fix is to first run

npm init

in the current directory, which interactively creates a package.json file that tells npm that we're creating a package in that directory, and any dependencies need to be local to the package, hence requiring that node_modules/ and thereby node packages be installed locally.

Following the creation of package,json, install commands run in that directory will install packages such as express locally.

Upvotes: 1

Niels
Niels

Reputation: 557

I asked this back when I was a terminal noob. The solution was simple:

cd (navigate using the command line) to the directory you want to install the module in and then it should work fine. It is a good idea to npm init first.

Upvotes: 3

Related Questions