Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save KiranMantha/81889edd1d25279984789f4c2936a228 to your computer and use it in GitHub Desktop.
Save KiranMantha/81889edd1d25279984789f4c2936a228 to your computer and use it in GitHub Desktop.
Pass cli args to nodejs program and read them
// index.js
const getArgs = () =>
  process.argv.reduce((args, arg) => {
    // long arg
    if (arg.slice(0, 2) === "--") {
      const longArg = arg.split("=");
      const longArgFlag = longArg[0].slice(2);
      const longArgValue = longArg.length > 1 ? longArg[1] : true;
      args[longArgFlag] = longArgValue;
    }
    // flags
    else if (arg[0] === "-") {
      const flags = arg.slice(1).split("");
      flags.forEach((flag) => {
        args[flag] = true;
      });
    }
    return args;
  }, {});

const args = getArgs();
console.log(args);

Examples:

  1. calling inline:

node index.js -D --name=Hello => { D: true, name: 'Hello' }

  1. calling via package.json
// package.json
{
  "scripts": {
    "start": "node index.js"
  }
}

npm start -- -D --name=Hello => { D: true, name: 'Hello' }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment