检查是否从Node.js脚本中安装了软件包

Check if package installed from within Node.js script

我正在尝试使用node.js编写脚本。

我有一个脚本,在这里我检查./node_modules/some-package的存在。如果不存在,则安装some-package

不过,这似乎有点老土。

是否有更好的方法检查脚本中是否安装了特定的包?

样本代码

1
2
3
4
5
6
7
8
9
const fs = require('fs');
let installed;

try {
  fs.accessSync('./node_modules/.bin/some-package');
  installed = true;
} catch (err) {
  installed = false;
}


问题方法的一个问题可能是,node_modules文件夹的路径可能被更改(NPM本地安装包到自定义位置)。

利用NPM获取已安装软件包信息的一种方法是通过npm ls

以下调用将返回已安装的some-package版本:

1
npm ls some-package

如果包存在,则打印版本信息,否则打印(empty)。如果要分析响应,请使用--jsoncli标志。

如果您对包是否存在感兴趣,可以使用退出代码:如果包存在,则为0,否则为非零。*

另外:关于如何从node js执行shell命令,请参阅使用node.js执行命令行二进制文件。

源:查找已安装的NPM包的版本,https://docs.npmjs.com/cli/ls

*至少对于节点5.6.0的我来说


我相信NPM文档中有您想要的内容:

optionalDependencies

If a dependency can be used, but you would like npm to proceed if it cannot be found or fails to install, then you may put it in the optionalDependencies object. This is a map of package name to version or url, just like the dependencies object. The difference is that build failures do not cause installation to fail.

It is still your program's responsibility to handle the lack of the dependency. For example, something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
try {
  var foo = require('foo')
  var fooVersion = require('foo/package.json').version
} catch (er) {
  foo = null
}
if ( notGoodFooVersion(fooVersion) ) {
  foo = null
}

// .. then later in your program ..

if (foo) {
  foo.doFooThings()
}

Entries in optionalDependencies will override entries of the same name in dependencies, so it's usually best to only put in one place.