WHITECOLOR WHITECOLOR - 11 months ago 97
Node.js Question

The best way to run npm install for nested folders?

What is the most correct way to install

npm packages
in nested sub folders?


What is the best way to have
be installed automatically when
npm install
run in


If you want to run a single command to install npm packages in nested subfolders, you can run a script via npm and main package.json in your root directory. The script will visit every subdirectory and run npm install.

Below is a .js script that will achieve the desired result:

var fs = require('fs')
var resolve = require('path').resolve
var join = require('path').join
var cp = require('child_process')

// get library path
var lib = resolve(__dirname, '../lib/')

  .forEach(function (mod) {
    var modPath = join(lib, mod)
// ensure path has package.json
if (!fs.existsSync(join(modPath, 'package.json'))) return

// install folder
cp.spawn('npm', ['i'], { env: process.env, cwd: modPath, stdio: 'inherit' })

Note that this is an example taken from a StrongLoop article that specifically addresses a modular node.js project structure (including nested components and package.json files).

As suggested, you could also achieve the same thing with a bash script.