简体   繁体   中英

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.

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.

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 (ie /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, ie /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.

Use

npm install packagename

This will install the dependencies in the local node_modules folder.

In global mode (ie, with -g or --global appended to the command), it installs the current package context (ie, the current working directory) as a global package.

So the default install location is local directory, and you need to specify -g or --global to install the modules globally.

Check out the official docs for more info: https://docs.npmjs.com/cli/install

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM