Monday, November 30, 2015

npm install taking a lot of time

Workaround:

Use http to connect to the npm registry as follows:

npm config set registry http://registry.npmjs.org/

Fix the dependencies to a version for dependencies present in package.json

npm install --save helps you to install/reinstall the dependencies and put their versions in package.json.

However, what if the packages are already installed with *s for the version in package.json and you want to be more specific about the versions in the package.json.  In that case, instead of using npm install --save and reinstall the packages, you can use this node script:

var packageJson, sys, exec, async, depJson, fs, deps;

sys = require('sys');
exec = require('child_process').exec;
async = require('async');
fs = require('fs');

packageJson = require(process.env.PWD + "/package.json");

deps = Object.keys(packageJson.dependencies);
deps = deps.concat(Object.keys(packageJson.devDependencies));

async.each(deps,
    function (dep, cb) {
        console.log("Executing : npm ls --json " + dep);
        exec("npm ls --json " + dep, function (error, stdout) {
            var versionJson = JSON.parse(stdout);
            if (packageJson.dependencies[dep]) {
                packageJson.dependencies[dep] = "~" + versionJson.dependencies[dep].version;
            }
            if (packageJson.devDependencies[dep]) {
                packageJson.devDependencies[dep] = "~" + versionJson.dependencies[dep].version;
            }
            console.log(dep + ": " + versionJson.dependencies[dep].version);
            cb();
        });
    },
    function (err) {
        if (err) {
            console.error("Following error occurred; not modifying package.json");
            console.error(err);
            return;
        }
        fs.writeFile(process.env.PWD + "/package.json", JSON.stringify(packageJson, null, 2));
    });