Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I npm install for current directory and also subdirectories with package.json files?

Tags:

node.js

npm

I have a an application which is a web game server and say for example I have node_modules which I use in directory ./ and I have a proper package.json for those. it happens that in directory ./public/ I have a website being served which itself uses node_modules and also has a proper package.json for itself.

I know I can do this by navigating the directories. But is there a command or way to automate this so that it is easier for other developers to bootstrap the application in their system?

like image 562
Elemenofi Avatar asked May 20 '15 02:05

Elemenofi


People also ask

Does npm install install everything in Package json?

By default, npm install will install all modules listed as dependencies in package. json .

Which command is used to generate a package json file in the current directory?

To create a default package. json using information extracted from the current directory, use the npm init command with the --yes or -y flag.

Can you npm install multiple packages?

Installing multiple packages using package. When you run the npm install command without specifying any package name, then npm will look for an existing package. json file in the current working directory. npm will install all packages listed as dependencies of the project.

How do I install multiple NPM packages in one command?

To install multiple packages, we need to use the npm install followed by the multiple package names separated by the spaces package1 package2 . This above command installs three packages, which are express, cors and body-parser. You can also checkout how to install the specific version of an npm package.


1 Answers

Assuming you are on Linux/OSX, you could try something like this:

find ./apps/* -maxdepth 1 -name package.json -execdir npm install \;

Arguments:

./apps/* - the path to search. I would advise being very specific here to avoid it picking up package.json files in other node_modules directories (see maxdepth below).

-maxdepth 1 - Only traverse a depth of 1 (i.e. the current directory - don't go into subdirectories) in the search path

-name package.json - the filename to match in the search

-execdir npm install \; - for each result in the search, run npm install in the directory that holds the file (in this case package.json). Note that the backslash escaping the semicolon has to be escaped itself in the JSON file.

Put this in the postinstall hook in your root package.json and it will run everytime you do an npm install:

"scripts": {
    "postinstall": "find ./apps/* -name package.json -maxdepth 1 -execdir npm install \\;"
}
like image 169
Rory Donohue Avatar answered Sep 20 '22 16:09

Rory Donohue