0

I'm trying to learn node Js, and I came across a few things that I can't figure out, I'm supposed to be able to do the "--filter" command or "filter" and the "--count" command or "count". And I'm supposed to be able to do the combination of both. For example do: "node app.js --filter=ry --count" or "node app.js --count --filter=ry" but for example for the latter it does not work unless filter is placed before count , here is my code.

try {
    const cmd = args[2].split("=");

    if (cmd[0] === '--filter' || cmd[0] === 'filter') {
        if (args.includes('--count') || args.includes('count')) {
            filter(cmd[1]);
            count();

        } else {
            filter(cmd[1]);

        }
    } else if (cmd[0] === '--count' || cmd[0] === 'count') {
        if (args.includes('--filter') || args.includes('filter')) {
            filter(cmd[2]);
            console.log(cmd);
            count();
        } else {
            count();

        }
    } else {
        console.log('Wrong arguments');
    }
} catch (err) {
    throw err;
}

I tried several solutions, to be able to do --count before filter when I type it in command but I still can't filter and count if the filter is not placed first

XeilaS
  • 1
  • Ideas on [parsing the command line in Node.js](https://stackoverflow.com/questions/4351521/how-do-i-pass-command-line-arguments-to-a-node-js-program). – jarmod Feb 22 '23 at 17:06
  • 1
    Just set variables when you're processing the command-line arguments. After that, take actions based on the variables. Then the order of the arguments won't matter. – Barmar Feb 22 '23 at 17:43
  • This `const cmd = args[2].split("=");` is hard-coding the position you're expecting the `--filter=ry` to be. Instead, you have to loop through all the arguments present and figure out which ones are which, not assume one particular option is always in the same place. – jfriend00 Feb 22 '23 at 17:49
  • This question has been answered in https://stackoverflow.com/questions/4351521/how-do-i-pass-command-line-arguments-to-a-node-js-program But just change line 2 to const cmd = process.argv[2].split("="); – imaCoden Feb 22 '23 at 17:59

0 Answers0