NPM NodeJS API没有很好的记录,但检查代码有帮助。
Here我们发现以下字符串:
install.usage = "npm install"
+ "\nnpm install <pkg>"
+ "\nnpm install <pkg>@<tag>"
+ "\nnpm install <pkg>@<version>"
+ "\nnpm install <pkg>@<version range>"
+ "\nnpm install <folder>"
+ "\nnpm install <tarball file>"
+ "\nnpm install <tarball url>"
+ "\nnpm install <git:// url>"
+ "\nnpm install <github username>/<github project>"
+ "\n\nCan specify one or more: npm install ./foo.tgz [email protected] /some/folder"
+ "\nIf no argument is supplied and ./npm-shrinkwrap.json is "
+ "\npresent, installs dependencies specified in the shrinkwrap."
+ "\nOtherwise, installs dependencies from ./package.json."
我的问题是关于版本,所以我们可以这样做:[email protected]
安装0.0.1
版hello-world
。
var npm = require("npm");
npm.load({
loaded: false
}, function (err) {
// catch errors
npm.commands.install(["[email protected]"], function (er, data) {
// log the error or data
});
npm.on("log", function (message) {
// log the progress of the installation
console.log(message);
});
});
我没有测试,但我相信,我们可以使用install.usage
解决方案的任何格式。
我写了一个函数,可以将数组中的dependencies
对象转换为可以传递给install
函数调用的数组。
dependencies:
{
"hello-world": "0.0.1"
}
的函数获取路径package.json
文件,并返回字符串的数组。
function createNpmDependenciesArray (packageFilePath) {
var p = require(packageFilePath);
if (!p.dependencies) return [];
var deps = [];
for (var mod in p.dependencies) {
deps.push(mod + "@" + p.dependencies[mod]);
}
return deps;
}
我刚刚测试了模块@版本方法,它确实有效。 – tremor
这很好,但是,如何以编程方式使用npm安装GLOBALY? –
@cSn检查我发现的代码[这段代码](https://github.com/npm/npm/blob/a362c3f1919987419ed8a37c8defa19d2e6697b0/lib/install.js#L122-L162) - 但是我不知道代码应该如何看起来像......也许你可以问一个问题。 –