我如何使用NPM在本地检查包,只有当前与想要的。不要尝试获取最新版本

时间:2017-02-07 20:15:04

标签: node.js npm githooks

我正在使用'npm oudated'命令,唯一的问题是它有点慢,因为它实际上也计算出最新版本的npm软件包。

理想情况下,我只是想知道本地是否缺少软件包,如果缺少软件包,则运行npm install。

我创建了这个脚本作为post-checkout githook,有没有更好的方法来检查你是否缺少package.json中的包?

#!/usr/bin/env node

var exec = require('child_process').exec,
    missingPackage = false;

return new Promise((resolve) => {
        exec('npm outdated --json', (error, stdout, stderr) => {
            resolve(JSON.parse(stdout));
        })
    })
    .then((packageJson) => {
        for (const x of Object.keys(packageJson)) {
            if (packageJson[x].location === '' ) {
                missingPackage = true;
            }
        }
    })
    .then(() => {
        if (missingPackage) {
            console.log('\nHello, you are missing some packages so we are going to install them....');
            exec('npm install', (error, stdout, stderr) => {
                console.log(stdout);
            })
        }
    })

1 个答案:

答案 0 :(得分:0)

我在NPM文档中没有看到任何内容,所以我就创建了这个。需要不到一秒的时间来检查您是否缺少包裹

#!/usr/bin/env node

const exec = require('child_process').exec,
    fs = require('fs'),
    packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8')),
    dependenciesPackages = Object.keys(packageJson.dependencies),
    devDependenciesPackages = Object.keys(packageJson.devDependencies),
    allNpmPackages = dependenciesPackages.concat(devDependenciesPackages);

// Checking if any packages are missing
return new Promise((resolve) => {
    for (const [idx, npmPackage] of allNpmPackages.entries()) {
        fs.readFile(`node_modules/${npmPackage}/package.json`, 'utf8', function(err) {
            if (err && err.code === 'ENOENT') {
                resolve(true);
            } else if (idx === allNpmPackages.length - 1) {
                resolve(false);
            }
        });
    }
})
// If packages are missing then run npm install
.then((isMissingPackages) => {
    if (isMissingPackages) {
        console.log('\nHello, you are missing some packages so we are going to install them....'); // eslint-disable-line no-console
        exec('npm install', (error, stdout) => {
            console.log(stdout); // eslint-disable-line no-console
        });
    }
});