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:

const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');

const result = {
    success: [],
    failure: []
};

function runNpmInstall(directory) {
    return new Promise((resolve) => {
        console.log(`Found ${directory}, running npm install...`);
        exec('npm install', { cwd: directory }, (error, stdout, stderr) => {
            if (error) {
                console.error(`Error installing dependencies in ${directory}: ${stderr}`);
                result.failure.push(directory);
                resolve(false);
            } else {
                console.log(`Successfully installed dependencies in ${directory}`);
                result.success.push(directory);
                resolve(true);
            }
        });
    });
}

async function findAndInstallDependencies(dir) {
    const files = fs.readdirSync(dir);

    for (const file of files) {
        const fullPath = path.join(dir, file);
        const stat = fs.statSync(fullPath);

        if (stat.isDirectory()) {
            const packageJsonPath = path.join(fullPath, 'package.json');
            if (fs.existsSync(packageJsonPath)) {
                await runNpmInstall(fullPath);
            } else {
                await findAndInstallDependencies(fullPath);
            }
        }
    }
}

async function main() {
    const currentDir = process.cwd();
    console.log(`Starting to find and install dependencies from ${currentDir}`);
    await findAndInstallDependencies(currentDir);

    console.log('\nInstallation Summary:');
    console.log('Successful installations:', result.success);
    console.log('Failed installations:', result.failure);
}

main().catch(err => {
    console.error('Error during installation process:', err);
});
Code language: JavaScript (javascript)
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments