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

How do I use NPM to check packages locally, only current vs wanted. Don't to try and fetch latest version

我正在使用 '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);
            })
        }
    })

我在 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
        });
    }
});