Skip to content
Advertisement

Javascript argparse with JSON config

I’m trying to integrate argparse into my Javascript program, such that all arguments can be loaded from an external config file, and then those values can be overridden with provided CLI arguments afterwards. To do this, I decided to read a config file & parse it into a JSON object, then iterate through the keys and set the default values in the parser, and finally parse any remaining CLI arguments to override the defaults. Unfortunately, I’m getting some strange behavior back, and since it’s a port of the Python repository there’s not much syntactically-relevant documentation (https://www.npmjs.com/package/argparse)

I have the following logic:

JavaScript

However, it looks like the parser.set_defaults() line isn’t working correctly:

JavaScript

Why is it trying to create a new config option “key”, even though the key passed into set_defaults() is a variable & has a new value every time it’s logged to the console?

Advertisement

Answer

I contributed to this repository years ago, but haven’t worked with it or javascript recently.

In python argparse, I think this is what you want to do:

JavaScript

or simply set all keys at once:

JavaScript

In Python (**conf) is equivalent to (path='..data...', json='../build', etc).

The action of set_defaults is to add to the _defaults attribute:

JavaScript

The python code is:

JavaScript

The corresponding javascript code is:

JavaScript

I don’t remember enough javascript to say whether that’s correct or not.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement