CommonDocs.org

Recursive npm package install

Here's a simple script that recursively searches through a folder, finds any instances of package.json, and runs npm install to install any dependencies needed at that location.

Instructions:

  • Save the script below in the root folder where you want the search to start from. For example, "npm-installer.js"
  • Run the script with node: "node npm-installer.js"
  • Wait

The script will identify each package.json file it finds, tell you it's running, and let you know if it succeeded. If it fails for some reason, any messages returned by npm will be displayed.

At the end, you'll see all the installations that succeeded or failed.

Here's the script:

javascript
1const fs = require('fs');
2const path = require('path');
3const { exec } = require('child_process');
4
5const result = {
6    success: [],
7    failure: []
8};
9
10function runNpmInstall(directory) {
11    return new Promise((resolve) => {
12        console.log(`Found ${directory}, running npm install...`);
13        exec('npm install', { cwd: directory }, (error, stdout, stderr) => {
14            if (error) {
15                console.error(`Error installing dependencies in ${directory}: ${stderr}`);
16                result.failure.push(directory);
17                resolve(false);
18            } else {
19                console.log(`Successfully installed dependencies in ${directory}`);
20                result.success.push(directory);
21                resolve(true);
22            }
23        });
24    });
25}
26
27async function findAndInstallDependencies(dir) {
28    const files = fs.readdirSync(dir);
29
30    for (const file of files) {
31        const fullPath = path.join(dir, file);
32        const stat = fs.statSync(fullPath);
33
34        if (stat.isDirectory()) {
35            const packageJsonPath = path.join(fullPath, 'package.json');
36            if (fs.existsSync(packageJsonPath)) {
37                await runNpmInstall(fullPath);
38            } else {
39                await findAndInstallDependencies(fullPath);
40            }
41        }
42    }
43}
44
45async function main() {
46    const currentDir = process.cwd();
47    console.log(`Starting to find and install dependencies from ${currentDir}`);
48    await findAndInstallDependencies(currentDir);
49
50    console.log('\nInstallation Summary:');
51    console.log('Successful installations:', result.success);
52    console.log('Failed installations:', result.failure);
53}
54
55main().catch(err => {
56    console.error('Error during installation process:', err);
57});
Was this guide useful?

Spotted a mistake? Select the sentence in the guide and choose “Suggest a fix”.

Comments

Found an error? instead, it reaches me faster.

No comments yet. Questions and corrections are welcome.