0

I have a root directory with a lot of child directories. I want to run npm install in each directory if a file with name package.json is present in that directory. I have to still consider some scenarios as below

After running npm install, it will create a new directory node_modules. If I re-run the command it should not check package.json present inside a directory with name node_modules.

I have tried

find . -name "package.json" -exec npm i \;
  • I think you're pretty close to the solution. npm i needs a foldername and with ``-exec npm i {} \;`` -- {} is the found file, but you need the folder of the file. I'm no bash expert, but something like this may work ``-exec npm i dirname {} \;`` via: https://stackoverflow.com/questions/6121091/get-file-directory-path-from-file-path – Gordon Mohrin Mar 28 '19 at 11:48
  • Thanks, @GordonMohrin. It works for now. But the next major step is, I should be able to rerun the command. When I re-run It should go into a particular folder with name node_modules. – Subhakant Priyadarsan Mar 30 '19 at 05:39

2 Answers2

1

What worked for me was (using Yarn package manager):

find . -type f -name package.json -exec bash -c 'yarn install --cwd $(dirname {})' \;

This command finds all package.json files recursively from current working directory. Then it executes a command (e.g. yarn install --cwd) with the pathname of the found package.json file.

You can use this command with npm install as well:

find . -type f -name package.json -exec bash -c 'npm install $(dirname {})' \;

You can optionally add -maxdepth N to the find command to limit the depth of the recursive find. This is to prevent a long running command because packages in node_modules folders have their own package.json files.

QNimbus
  • 355
  • 2
  • 6
0

Exclude node_modules directory

find . -type f -name package.json -not -path "*/node_modules/*" -exec bash -c 'cd $(dirname {}) && npm install && npm audit fix' \;
Alex
  • 388
  • 3
  • 4