15

If I have a foo.js node script, is there a way for me to automatically install all the npm dependencies?

e.g. If foo.js had this:

var program = require('commander');
var cheerio = require('cheerio');

Is there any npm command or something that I could do that would read foo.js and do 'npm install commander;npm install cheerio'?

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
sivano
  • 619
  • 1
  • 6
  • 12
  • to install the dependencies `automatically` , first of all list them `manually` in `package.json` file and run the `npm install`(sometimes `sudo npm install`) command. – Lekhnath Mar 02 '14 at 07:54
  • Possible duplicate of [Is it possible to automatically install the required modules for a node.js script?](http://stackoverflow.com/questions/14226025/is-it-possible-to-automatically-install-the-required-modules-for-a-node-js-scrip) – Anderson Green Sep 10 '16 at 01:17

3 Answers3

16

List your dependencies in a package.json file. You can then run npm install to install all dependencies.

Here's an example of a package.json file. Notice how dependencies are defined:

{
  "name": "best-practices",
  "description": "A package using versioning best-practices",
  "author": "Charlie Robbins <charlie@nodejitsu.com>",
  "dependencies": {
    "colors": "0.x.x",
    "express": "2.3.x",
    "optimist": "0.2.x"
  },
  "devDependencies": {
    "vows": "0.5.x"
  },
  "engine": "node >= 0.4.1"
}

Source: https://blog.nodejitsu.com/package-dependencies-done-right/

Ayush
  • 41,754
  • 51
  • 164
  • 239
  • 2
    Thank you for the answer and useful link, let me read up on it! I was (naively?) hoping there was a programmatic way to extract the dependencies from the .js file itself. I'll read through the package dependencies link you posted. – sivano Mar 02 '14 at 13:49
9

There is now a tool that auto-installs required dependencies as you code.

It's called auto-install.

enter image description here

0

npm-install-peers is a npm package that will detect peers and install them.

Note that you should install it globally

Luca C.
  • 11,714
  • 1
  • 86
  • 77