I am creating a cli app using node js & vorpal. There is no syntax error or warnings and everything works perfectly except that vorpal log doesn't work. Below is a small code snippet.
//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();
As I said everything works fine & the directory is created but no log is displayed.
What I've Tried : Using app.log & using app.session.log. It does not even log custom strings, example : this.log('Hello')
System : Windows
The makeDir
function should be coded to accept a callback and call it when done with the appropriate information passed, like below:
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;
Then you can do:
functions.makeDir(name,location,function(err,msg) {
if (err) this.log(err);
this.log(msg); //nothing gets logged
} /* callback now is accepted */ );
In your action.
PS make sure you bind the this
reference to your callback, for example using Function.prototype.bind
so you dont get funny results when using this.log
inside the callback