日志功能在使用 vorpal js 的 cli 应用程序中不起作用

Log function not working in cli app using vorpal js

我正在使用 node js 和 vorpal 创建一个 cli 应用程序。没有语法错误或警告,除了 vorpal 日志不起作用外,一切正常。下面是一小段代码。

//functions.js

const mkdir = require('mkdirp');

function makeDir(dirname,location) {
    let p = `${location}/${dirname}`;
    mkdir(p, function(err) {
        if (err) return err;
        return `Directory ${dirname} created !`;
    });
}
module.exports.makeDir = makeDir;

//main.js

const app = require('vorpal')();
const functions = require('./functions');

app
    .command('newdir <name> <location>', 'Create new database')
    .action(function(args,cb) {
        let name = args.name;
        let location = args.location;
        functions.makeDir(name,location,function(err,msg) {
            if (err) this.log(err);
            this.log(msg);  //nothing gets logged
        });
        cb();
    });

app
.delimiter('app $')
.show();

如我所说,一切正常,目录已创建,但未显示任何日志。

我试过的方法:使用 app.log 和使用 app.session.log。它甚至不记录自定义字符串,例如:this.log('Hello')

系统:Windows

makeDir 函数应编码为接受回调并在完成时调用它并传递适当的信息,如下所示:

const mkdir = require('mkdirp');

function makeDir(dirname,location, callback /* accept a callback */ ) {
    let p = `${location}/${dirname}`;
    mkdir(p, function(err) {
        if (callback)
          callback(err ? err : null, err? null : `Directory ${dirname} created !`);
    });
}
module.exports.makeDir = makeDir;

然后你可以这样做:

functions.makeDir(name,location,function(err,msg) {
  if (err) this.log(err);
  this.log(msg);  //nothing gets logged
} /* callback now is accepted */ );

在你的行动中。

PS 确保将 this 引用绑定到回调,例如使用 Function.prototype.bind 这样在回调中使用 this.log 时就不会得到有趣的结果