NPM Installs Package Outside Current Directory

2019-01-18 09:52发布

问题:

I try to install express package using npm from inside /home/iwan/my-project directory:

npm install express

express@3.3.7 ../node_modules/express
├── methods@0.0.1
├── cookie-signature@1.0.1
├── range-parser@0.0.4
├── fresh@0.2.0
├── buffer-crc32@0.2.1
├── cookie@0.1.0
├── debug@0.7.2
├── send@0.1.4 (mime@1.2.11)
└── commander@1.2.0 (keypress@0.1.0)

The strange thing is npm doesn't install express package in current dir (/home/iwan/my-project/node_modules/express), but in /home/iwan/node_modules/express.

Did i miss something?

回答1:

If the node_modules directory doesn't exist in your current directory, NPM will look for it in the higher directories until it finds it. So, if the parent directory has a node_modules directory, NPM will assume that's where it is to install modules.

A quick way around this is to create an empty node_modules directory where you want the modules to be placed.



回答2:

I believe the best way to install packages with npm is to make a package.json file. Like this, just put it in the smae directory as your app. A sample package.json file could look like this:

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.3.5",
    "jade": "*",
    "less-middleware": "*",
    "ejs": "*",
    "mongoose": "3.6.*"
  }
}

Take a look at the dependencies list. Just add the module that you want, for example, underscore. Just add it to the dependencies dict. Like so:

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "3.3.5",
    "jade": "*",
    "less-middleware": "*",
    "ejs": "*",
    "mongoose": "3.6.*",
    "underscore": "*"   <-------------- Added
  }
}

Then head over to your directory and just run npm install, and bam! All the packages and their dependencies will be installed for you. It will do all the work, and that means making your node_modules folder for you. This is how my app directory looks like:



回答3:

You could also create a blank package.json file using guidelines from the https://docs.npmjs.com/files/package.json webpage. Then place this in your project folder and type npm install.



标签: node.js npm