arg
arg copied to clipboard
Flags with optional values
Is there a way to have optional flag values? Something like the following:
const arg = require('arg');
const args = arg({
'--port': Number, // --port <number>
'--host': String.optional, // --host [string]
});
Given --port 5432 --host localhost
it should return { _: [], port: 5432, host: 'localhost' }
,
given --port 5432 --host
it should return something like { _: [], port: 5432, host: true }
,
and given --port 5432
it should return { _: [], port: 5432 }
,
I'd like this for ts-node to emulate the behavior of node's -p
flag. node -p 123
is equivalent to node -pe 123
Workaround is to pass the permissive flag and use a string type, then find the arg value manually:
// cmd.js
const defaultSince = 'origin/main';
const { _ = [], ..args } = arg({
'--since': defaultSince
}, { permissive: true });
console.log(_);
const sinceIndex = _.indexOf('--since');
if (sinceIndex > -1) {
console.log(_[sinceIndex + 1]);
}
node cmd.js --since develop
# [ '--since', 'develop' ]
# develop