无法访问现有节点包的属性,因为它是'未定义'为什么

Cannot access property of an existing node package because it is 'undefined'. Why?

本文关键字:因为 为什么 未定义 属性 访问 节点      更新时间:2023-09-26

我一直在玩node.js -构建Wordpress设置工具,使用wp-cli包作为依赖项。我有一个功能包,它执行了几个步骤(下载文件,创建配置/本地数据库,执行一些WP管理任务等),但它是回调地狱的一个主要例子,所以我选择将负载分配到一个对象上。

下面是一个简化的模块,说明我尝试这样做,直到它失败的地方。我也把收到的错误信息贴出来了。

我要重申,在重构之前一切都很好——我知道config/options对象是有效的,wp-cli包肯定能工作。在过去的项目中,我使用了'var foo = this;'技术来保留上下文,但错误似乎表明wpcli没有被保留。

任何建议将不胜感激!


代码:

module.exports = function(config, options) {
    var wpcli = require('wp-cli');
    function WpInstaller (wpcli, config, options) {
        this.wpcli = wpcli;
        this.config = config;
        this.options = options;
        this.init();
    };
    WpInstaller.prototype.init = function() {
        var wpinst = this;
        wpinst.wpcli.discover({path: wpinst.options.name.default}, function() {
            wpinst.downloadCore();
        });
    };
    WpInstaller.prototype.downloadCore = function() {
        var wpinst = this;
        wpinst.wpcli.core.download(function(err, res) {
            if (err) return false;
            wpinst.setupConfig();
        });
    };
    new WpInstaller(wpcli, config, options);
};

错误:

TypeError: Cannot read property 'download' of undefined
    at WpInstaller.downloadCore (/Users/john/dev/wpack/lib/wordpress.js:38:18)
    at /Users/john/dev/wpack/lib/wordpress.js:31:11
    at /Users/john/dev/wpack/node_modules/wp-cli/lib/WP.js:119:3
    at /Users/john/dev/wpack/node_modules/wp-cli/lib/commands.js:76:4
    at ChildProcess.exithandler (child_process.js:735:7)
    at ChildProcess.emit (events.js:110:17)
    at maybeClose (child_process.js:1008:16)
    at Process.ChildProcess._handle.onexit (child_process.js:1080:5)

wpcli.discover()是一个静态方法,它创建一个新的WP实例并将该实例传递给回调。该实例包含命令。所以试试这样写:

var wpcli = require('wp-cli');
function WpInstaller (config, options) {
  this.wp = null;
  this.config = config;
  this.options = options;
  this.init();
};
WpInstaller.prototype.init = function() {
  var wpinst = this;
  wpcli.discover({path: wpinst.options.name.default}, function(wp) {
    wpinst.wp = wp;
    wpinst.downloadCore();
  });
};
WpInstaller.prototype.downloadCore = function() {
  var wpinst = this;
  wpinst.wp.core.download(function(err, res) {
    if (err) return false;
    wpinst.setupConfig();
  });
};
module.exports = function(config, options) {
  new WpInstaller(config, options);
};
相关文章: