Skip to content

Programmatically expose whether a cli flag takes an argument or not #54144

Closed as not planned
@nicolo-ribaudo

Description

@nicolo-ribaudo

What is the problem this feature will solve?

I am trying to build a wrapper around the Node.js CLI, and for that I need to know which flags are meant to be passed to Node.js and which one should be passed to the script.

I was hoping that process.allowedNodeEnvironmentFlags would help with this, but unfortunately it's not enough. Consider this two commands:

node --some-flag --some-other-flag foo bar --baz

And assume that process.allowedNodeEnvironmentFlags includes --some-flag and --some-other-flag. What are the arguments being passed to node, and what to the script? which script?

There are two possible answers:

  • --some-other-flag takes a value, so --some-flag --some-other-flag foo are for node, the script is bar, and --baz is in process.argv;
  • --some-other-flag does not take a value, so --some-flag --some-other-flag are for node, the script is foo, and bar --baz is in process.argv.

What is the feature you are proposing to solve the problem?

Make process.allowedNodeEnvironmentFlags a map with boolean values telling whether the flag takes a value or not. The logic to use it would then become:

function splitArgs(allArgs) {
  let nodeArgs = [];
  let scriptName;
  let scriptArgs = [];

  let i = 0;
  while (i < allArgs.length && allArgs[i][0] === "-") {
    nodeArgs.push(allArgs[i]);
    if (process.allowedNodeEnvironmentFlags.get(allArgs[i])) nodeArgs.push(allArgs[++i]);
    i++;
  } 
  scriptName = allArgs[i++];
  while (i < allArgs.length) scriptArgs.push(allArgs[i++]);

  return { nodeArgs, scriptName, scriptArgs };
}

For backward compatibility, this map should still have a no-op .add method.

What alternatives have you considered?

I can hard-code the list. However, this means that for every new release I have to check if there is any change in the supported flags, and I have to maintain multiple lists one per version.

The maintenance cost for Node.js is much lower, given that new flags already have to be added to process.allowedNodeEnvironmentFlags anyway.

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestIssues that request new features to be added to Node.js.stale

    Type

    No type

    Projects

    Status

    Awaiting Triage

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions