1

I'm creating a CLI using Nodejs and commander and i need to implement an option/command like this.

--create user --f-name="Kevin"

I tried various options but could get it working

#!/usr/bin/env node
const program = require("commander");

function collect(val, memo) {
  memo.push(val);
  return memo;
}

program.version("0.0.1", "-v, --version")
.option(
    "-c, --create <items>",
    "Create user",
    collect,
    []
  ).parse(process.argv);

console.log(' collect: %j', program.create );

This works only when i execute with like this --create user,a,d,v and it gives out an array collect: ["user,a,d,v"]. Any idea on how to implement this using Commander.js

TRomesh
  • 3,786
  • 5
  • 38
  • 61
  • I am not sure I understand what you are trying to do. I assume from the title and the code you want to supply multiple values for `--create` and it looks like you are close, but what is the `--f-name` in your example? – shadowspawn Jun 13 '19 at 20:40

1 Answers1

-1

Try this script:

program
  .option('-c, --create', 'Create User')
  .option('-un, --user-name <type>', 'Username');
  
program.parse(process.argv);

console.log(program.userName, `userName: ${program.userName}`)

And execute like this from the terminal:

node command.js --create user --user-name=NameUser
KyleMit
  • 45,382
  • 53
  • 367
  • 544
  • i need to check the value/command entered by the user just after the flag `--create`. In this case it will be `user` – TRomesh Jun 12 '19 at 19:17
  • Ok so: `.option('-c, --create ', 'Create User')` note that I added **** after `--create` and then you can use a comparation like this `program.create === "user"` or use a switch statement. – Javier Jaimes Jun 12 '19 at 19:40
  • Small correction, the short option flag is only a single character so `-u` or `-n`, but not `-un`. – shadowspawn Jun 13 '19 at 20:43