kaziutus
kaziutus

Reputation: 148

Terminal does not show yargs' handler value

I am learning node.js and I have first problem. After I have installed yargs and I am trying to create yargs command but it does not show in the terminal. When I type node app.js mycommand in terminal it only returns me the array of args, not my command, but if I type 'node app.js --help' it returns each command. Am I doing something wrong?

const yargs = require('yargs')

 yargs.command({
     command: 'mycommand',
     describe: 'mydesc',
     handler: () => { console.log('some text') } })

I would like to have my console.log displays 'some text' when I type 'node app.js mycommand' but actually I have only array of args:

{ _: [ 'mycommand' ], '$0': 'app.js' }

Upvotes: 1

Views: 888

Answers (3)

Anand Raja
Anand Raja

Reputation: 3108

Your code is write only. But you are not displaying the commands. That's the reason you are not seeing anything. You can fix this in two ways.

  1. console.log(yargs.argv)

  2. yargs.parse()

either of these should be added after finishing your code.

PS: If you use console.log(yargs.argv) , argv object will be printed along with your desired result.

If still getting confused, feel free to check below code

const yargs = require('yargs');

 yargs.command({
     command: 'mycommand',
     describe: 'mydesc',
     handler: () => { console.log('some text') } 
    });

yargs.parse();

Upvotes: 0

Mo Sa
Mo Sa

Reputation: 161

Either use yargs.argv; or .parse()

yargs.command({
  command: 'add',
  describe: 'This is add param',
  handler: function() {
    console.log("This is add notes command ");
  }
});
yargs.argv;

or

yargs.command({
  command: 'add',
  describe: 'This is add param',
  handler: function() {
    console.log("This is add notes command ");
  }
}).parse();

to run it...

node app.js add

Upvotes: 0

Yilmaz
Yilmaz

Reputation: 49341

You should add .parse() to the end of your code. That is all.

const yargs = require('yargs')

 yargs.command({
     command: 'mycommand',
     describe: 'mydesc',
     handler: () => { console.log('some text') } }).parse()

If you have too many commands like this, instead of using parse() for each command, just type this below your code:

yargs.parse()

Or type this below your code

console.log(yargs.argv)

However this will also print out the "argv" (arguments vector).

Upvotes: 0

Related Questions