Get a dictionary consisting of CLI arguments, parsed and statically typed.
Sometimes, a Node.js program needs to receive arguments from the CLI, like this:
node index.js usa hamburger react
If there is a large number of arguments, they can be annotated in a getopt-ish fashion, like this:
node index.js -country usa -food hamburger -library react
vardict
parses the arguments passed on to CLI and makes a dictionary/map object that can be used elsewhere in the program. For the previous example, it would work like this:
{ country: 'usa', food: 'hamburger', library: 'react' }
As mentioniod above, the rule of parsing is "getopt-ish", meaning that this package does not work in the exact same way as getopt does.
- Annotations with double hyphens or quotation marks are treated as single entities.
node index.js -name Noyan --home Narayanganj
will produce{ name: 'Noyan', home: 'Narayanganj' }
- Whitespaces and equal signs ('
=
') are treated as a separator between the annotation and the value.node index.js --state NSW --capital=Sydney
will generate{ state: 'NSW', capital: 'Sydney' }
- Static typing is enforced on the values, based on the literal inputs. For example,
true
/false
isboolean
, and numeric values arenumber
.node index.js -country BD -popDensPerSqKM 1116 -overPop true
will yield{ country: 'BD', popDensPerSqKM: 1116, overPop: true }
- If there is no value provided after an annotation, it is considered a
boolean
value and set totrue
.node index.js -country NZ -covidFree -pop 4886000 -neighbour
will output{ country: 'NZ', covidFree: true, pop: 4886000, neighbour: true }
.
- If the same key is supplied twice, they are merged into an array.
node index.js -country Australia -easternStates QLD -easternStates NSW -easternStates VIC -easternStates TAS
will give{ country: 'Australia', easternStates: ['QLD', 'NSW', 'VIC', 'TAS'] }
.node index.js -asl 28 -asl false -asl Sydney
will generate{ asl: [28, false, 'Sydney'] }
.
- If a key is followed by multiple properties, they are merged into an array.
node index.js -asl 28 false Sydney
will produce{ asl: [28, false, 'Sydney'] }
, the same as the previous example.
Add the package via command line.
NPM | Yarn | PNPM | Bun |
---|---|---|---|
npm i vardict |
yarn add vardict |
pnpm add vardict |
bun add vardict |
Just import and use the object:
// script.js
import vardict from 'vardict' // ES6
const { default: vardict } = require('vardict') // CommonJS
console.log(vardict)
Here are the input and the output of the code.
node script.js \
--'full name' 'Anirudha Paul' \
--age 25 \
--single \
-c 'Samsung R&D' \
--home Mymensingh \
--coolWithLadies false \
-wantsToGoTo=USA \
--IELTS=7.5 \
--favoriteFood kachchi \
-nick-name Prasun
{
'full name': 'Anirudha Paul',
age: 25,
single: true,
c: 'Samsung R&D',
home: 'Mymensingh',
coolWithLadies: false,
wantsToGoTo: 'USA',
IELTS: 7.5,
favoriteFood: 'kachchi',
'nick-name': 'Prasun'
}