简体   繁体   English

node.js:从模块内与npm对话

[英]node.js: Talk to npm from within a module

I'd like to add a self-updating feature to a globally installed module. 我想向全局安装的模块添加自我更新功能。 Is there a better way of doing it than this? 有没有比这更好的方法了?

require("child_process").exec("npm update -g module-name");

There's some documentation about installing npm as a local dependency. 有一些有关将npm安装为本地依赖项的文档 Is this necessary? 这有必要吗? Is there any sample code on how to execute commands like update or install ? 关于如何执行updateinstall等命令,是否有任何示例代码?

Here's what I've usually done to use the system copy of npm instead of installing another copy of npm as a local module: 这是我通常使用npm的系统副本而不是将npm的另一个副本安装为本地模块所做的工作:

function loadNpm(cb) {
  require('child_process').exec('npm', function(err, stdout, stderr) {
    var m = /npm@[^ ]+ (.+)\n/i.exec(stdout);
    if (!m)
      return cb(new Error('Unable to find path in npm help message'));
    cb(undefined, require(m[1]));
  });
}


// usage ...
// only need to call `loadNpm()` once
loadNpm(function(err, npm) {
  if (err) throw err;
  // load() is required before using npm API
  npm.load(function(err, npm) {
    if (err) throw err;
    // e.g. npm.search('ssh', true, function(err, results) { console.dir(results); });
  });
});

Depending on your goals, here are a few options: 根据您的目标,有以下几种选择:

1) Via exec() as you mention. 1)通过您提到的exec()。 Don't forget to add an error callback. 不要忘记添加错误回调。

2) Using the npm package as you mention. 2)使用您提到的npm软件包。

For example, I wrote a quick script to install the Yeoman package globally which worked well. 例如,我编写了一个快速脚本来在全球范围内安装Yeoman软件包,效果很好。 I didn't see a lot of documentation for this so I started reading the source code in the npm package itself. 我没有看到太多关于此的文档,所以我开始阅读npm包本身中的源代码。

var npm = require('npm');

npm.load (function (err, npm) {
    if (err) {
        console.log("Error loading");
        return;
    }

    npm.config.set('global', true);
    npm.commands.install(['yo'], function (err)  {
        if (err) {
            console.error("Installation failed");
        }
    });
});

3) Another option is to just have a cron job auto-update packages if that is your goal. 3)另一个选择是,如果您的目标是仅拥有cron作业自动更新程序包。

4) You may also be interested in this package https://github.com/tjunnone/npm-check-updates 4)您可能也对此软件包感兴趣https://github.com/tjunnone/npm-check-updates

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

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