我一直在使用node.js - 构建一个Wordpress设置工具,使用wp-cli包作为依赖项。我有一个功能包,它执行了几个步骤(下载文件,创建配置/本地数据库,执行一些WP管理任务等),但它是Callback Hell的一个主要示例,所以我选择在一个对象上分配负载。
下面是一个精简模块,说明我尝试这样做,直至失败。我还发布了收到的错误消息。
我会重申在重构之前一切正常 - 我知道 config / 选项对象是有效的, 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)
答案 0 :(得分:1)
wpcli.discover()
是static method creates a new WP
instance和passes that instance to the callback。 That instance is what contains the commands。所以尝试这样的事情:
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);
};