node.jscommand-line-interfacenode-commander

Get multiple command option using commander


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


Solution

  • Try this script:

    program
      .option('-c, --create', 'Create User')
      .option('-u, --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