简体   繁体   English

从节点脚本获取安装的npm版本?

[英]Get installed version of npm from node script?

I check the globally installed Node version in my build script: 我在构建脚本中检查全局安装的Node版本:

var semver = require('semver');
var packageJson = require('./package.json');
var expectedVersion = packageJson.engines.node;

var actualVersion = process.version;
if (semver.neq(expectedVersion, actualVersion)) {
  fail('Incorrect Node version: expected ' + expectedVersion + ', but was ' + actualVersion);
}

I'd like to check the globally installed npm version in a similar manner. 我想以类似的方式检查全局安装的npm版本。 How can I retreive the globally installed npm version? 如何检索全局安装的npm版本?

It's not pretty, but this will do the trick: 它不漂亮,但这将成功:

var exec = require('child_process').exec,
npmVersion;

exec('npm -v',
  function (error, stdout, stderr) {
    npmVersion = stdout;
});

Note that it's async so you'll have to do the npm comparison in the callback, but the value contained in stdout should be a valid input to semver. 请注意,它是异步的,所以你必须在回调中进行npm比较,但是stdout中包含的值应该是semver的有效输入。

if by "similar manner" you mean examining npm's package.json file, then you'll have to know where in the filesystem it lives. 如果用“类似的方式”表示检查npm的package.json文件,那么你必须知道它所在的文件系统中的位置。 And that means knowing how npm was installed: it could be via a management tool like nvm or n , or it could be via your OS' software installation tool or package manager, or it could simply be in an arbitrary directory. 这意味着知道如何安装npm:它可以通过像nvmn这样的管理工具,也可以通过你的操作系统软件安装工具或包管理器,或者它可以只是在任意目录中。

Probably the easiest thing to do is to skip trying to find npm's package.json file and instead just use node's built-in Child Process module to execute npm -v and capture the output in a variable, then compare as necessary using semver. 可能最简单的方法是跳过尝试查找npm的package.json文件,而只是使用node的内置Child Process模块执行npm -v并在变量中捕获输出,然后根据需要使用semver进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM