Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am trying to run yargs command, and it is not working

Tags:

node.js

yargs

I am running:

node app.js add

And my code is:

const yargs = require('yargs');
yargs.command({
    command:'add',
    describe:'Adding command',
    handler:function(){
        console.log('Adding notes');
    },
})

But nothing printed on the console.

like image 407
Sugumar Venkatesan Avatar asked May 26 '19 13:05

Sugumar Venkatesan


People also ask

What does Yargs parse () do?

Parses a command line string, returning detailed information required by the yargs engine. expects: args : a string or array of strings representing options to parse. opts : provide a set of hints indicating how args , inputs are identical to require('yargs-parser')(args, opts={}) .


3 Answers

As @jonrsharpe mentioned in the comment above.

You need to either call parse function or access argv property

Try:

const yargs = require('yargs');

yargs
    .command({
        command:'add',
        describe:'Adding command',
        handler: argv => {
            console.log('Adding notes');
        }
    })
    .parse();

Or

const yargs = require('yargs');

const argv = yargs
    .command({
        command: 'add',
        describe: 'Adding command',
        handler: argv => {
            console.log('Adding notes');
        }
    })
    .argv;

node index.js add

like image 117
Ihor Sakailiuk Avatar answered Nov 16 '22 04:11

Ihor Sakailiuk


You have to provide the yargs.parse(); or yargs.argv; after defining all the commands.

const yargs = require('yargs');
yargs.command({
    command:'add',
    describe:'Adding command',
    handler:function(){
        console.log('Adding notes');
    },
});

yargs.parse();
//or
yargs.argv;

or

You can .argv or .parse() specify individually

    yargs.command({
        command:'add',
        describe:'Adding command',
        handler:function(){
            console.log('Adding notes');
        },
    }).parse() or .argv;
like image 35
3 revs, 2 users 62% Avatar answered Nov 16 '22 04:11

3 revs, 2 users 62%


This is okay if you have one command. But for multiple commands, do yargs.argv at last after defining all commands.

const yargs = require('yargs');
 
const argv = yargs
    .command({
        command: 'add',
        describe: 'Adding command',
        handler: argv => {
            console.log('Adding notes');
        }
    }).argv;

Example solution:

const yargs = require('yargs')

//add command
yargs.command({
    command: 'add',
    describe: 'Add a new note',
    handler: ()=>{
        console.log("Adding a new note")
    }
})
//remove Command
yargs.command({
    command: 'remove',
    describe: "Remove a Note",
    handler: ()=>{
        console.log("removing note")
    }
})

yargs.parse()
like image 28
Anirban Sinha Avatar answered Nov 16 '22 02:11

Anirban Sinha