Multi-customizable parser of process.argv for nodejs.
Fargv is a flag and command parser with the ability to configure options that tell fargv exactly how to handle a particular flag or command.
Fargv also provides processing of constructs such as objects and arrays using a special syntax that is very similar to javascript.
Fargv is sensitive to passed arguments and by default supports only the passed Latin alphabet, and the flags themselves must be passed using an equal sign.
If the first described situation can be expanded, then nothing can be done for the second, since this is the principle of correct operation of fargv.
Fargv has its own flag generator, which makes it easy to pass complex constructs between processes.
In General, Fargv can be a good option if you really need to configure argv parsing.
- Install
- Usage
- API
- fargv
- fargvReturns interface
- Description of fargvReturns
- fargvOptions interface
- Description of options
- help
- commands
- separateCommandHandler
- callAppropriateCommandHandlerOnlyOnce
- alwaysCallSeparateCommandHanler
- nextCommandsAsArray
- customArgv
- defaultArgv
- demandWithSkippedFlags
- demandFlags
- excludeFlags
- noParseFlags
- noParseNoDefaultFlags
- returnFilter
- rememberExecNodePath
- rememberExecFilePath
- rememberExecFileBasename
- rememberWarns
- showWarns
- parseWarn
- throwInsteadWarns
- includeEmptyFlags
- unlimitedFlagDefinitionCharacters
- supportOnlyLatinArgs
- defaultCommaSplitSym
- allowSpacesAsValues
- useDnvForFirstSpaceOP
- noParse
- noParseNoDefault
- allParse
- mainParse.defaultNoneValue
- mainParse.allTypes
- mainParse.mainTypes
- mainParse.minorTypes
- mainParse.numericSeparator
- mainParse.number
- mainParse.bigint
- mainParse.boolean
- mainParse.array
- mainParse.object
- mainParse.null
- mainParse.undefined
- mainParse.NaN
- mainParse.Infinity
- arrayParse
- objectParse
- Static methods
- options
- createOptions
- reset
- resetAll
- command
- separateCommand
- optionFlag
- optionVersion
- optionCommand
- help
- default
- custom
- customWithGenerate
- customWithGenerateFromObject
- demand
- undemand
- exclude
- noParse
- noParseFlags
- allParse
- returnFilter
- remember
- warns
- arrayParse
- objectParse
- state
- fromArray
- fromObject
- toArray
- toObject
- strIsArray
- strIsObject
- strIsStrictArray
- strIsStrictObject
- generate
- generateFromObject
- init
- Contacts
$ npm install fargv
const fargv = require("fargv");
const argv = fargv({
returnFilter: "flags",
defaultNoneValue: "someDefault",
noParseFlags: ["cc"],
numericSeparator: true,
boolean: true,
minorTypes: true,
});
console.log(argv);
$ node ./withoutStaticMethods.js ---a=true --b=2_000_000 -cc=1_000_000 -d=NaN -e
{ a: true, b: 2000000, cc: '1_000_000', d: NaN, e: 'someDefault' }
const fargv = require("fargv");
const { flags } = fargv
.options({ defaultNoneValue: "someDefault" })
.noParseFlags("c")
.options({ minorTypes: true, array: true })
.arrayParse({ bigint: true })
.init()
console.log(flags);
$ node ./withStaticMethods.js -a=NaN -b -cc="[1n, 2_000n]" --d=1n
{ a: NaN, b: 'someDefault', cc: [ 1n, '2_000n' ], d: '1n' }
Types: HERE!
Returns an object
with the following interface:
interface fargvReturns {
_?: {
execNodePath?: string,
execFilePath?: string,
execFileBasename?: string,
},
warns: null | string[],
flags: {
[key: string]: any,
},
commands: string[],
}
An additional object that remembers some paths and names based on the first 2 "system" arguments.
Path to node js.
Path to the executable file.
Executable file name.
If there are no errors and the "rememberWarns" parameter is not set - null. Otherwise, it is a string array of warnings that occur during parsing.
A flag object, where the name of the property is the flag name, and its value is the possibly parsed flag value.
String array of commands that were stored during parsing.
If you need to pass options from .js or .json file - the following structure is used:
type fargvOptionsFromFile = ["useConfigsFromFile", string]
Where the element at index 0 indicates that fargv really needs to process the incoming parameter as connecting a third-party configuration file. The second element is the path to the configuration file (we recommend using process.cwd with the path wrapper from the node.js).
The standard interface for options that are passed to fargv is as follows(fargvOptions):
interface mainParse {
defaultNoneValue?: any,
allTypes?: boolean,
mainTypes?: boolean,
minorTypes?: boolean,
numericSeparator?: boolean,
number?: boolean,
bigint?: boolean,
boolean?: boolean,
array?: boolean,
object?: boolean,
null?: boolean,
undefined?: boolean,
NaN?: boolean,
Infinity?: boolean,
}
interface fargvOptions extends mainParse {
help?: {
flagsToCall?: string[],
status?: boolean,
mainUsage?: string,
mainDesc?: string,
mainCustomEndText?: string,
showMainCommands?: boolean,
showMainFlags?: boolean,
showForSpecificCommand?: boolean,
showForSpecificFlag?: boolean,
showExamples?: boolean | "commands" | "flags",
showExamplesForSpecific?: boolean | "commands" | "flags",
exit?: boolean,
commands?: {
[key: string]: {
alias?: Array<string> | string,
desc?: string,
usage?: string,
flags?: Array<string> | string,
examples?: Array<string> | string,
},
},
flags?: {
[key: string]: {
desc?: string,
required?: boolean | string,
deprecated?: boolean | string,
empty?: boolean,
type?: "string" | "number" | "array" | "object" | "bigint" | "boolean",
alias?: Array<string> | string,
examples?: Array<string> | string,
}
},
},
//commandName, handler, aliases
commands?: ([string, Function, string[]])[],
separateCommandHandler?: (state: fargvReturns, ...nextCommands: string[]) => void,
callAppropriateCommandHandlerOnlyOnce?: boolean,
alwaysCallSeparateCommandHanler?: boolean,
nextCommandsAsArray?: boolean,
customArgv?: string[],
defaultArgv?: {
//value, aliases
[key: string]: [any, string[]]
},
demandWithSkippedFlags?: string[],
demandFlags?: string[],
excludeFlags?: string[],
noParseFlags?: string[],
noParseNoDefaultFlags?: string[],
returnFilter?: string | string[],
rememberExecNodePath?: boolean,
rememberExecFilePath?: boolean,
rememberExecFileBasename?: boolean,
rememberWarns?: boolean,
showWarns?: boolean,
parseWarn?: ({}: { mainMessage: string, debugDetails: { [key: string]: any }, code: number, fullMessage: string }) => void,
throwInsteadWarns?: boolean,
includeEmptyFlags?: boolean,
unlimitedFlagDefinitionCharacters?: boolean,
supportOnlyLatinArgs?: boolean,
defaultCommaSplitSym?: string,
allowSpacesAsValues?: boolean,
useDnvForFirstSpaceOP?: boolean,
noParse?: boolean,
noParseNoDefault?: boolean,
allParse?: boolean,
mainParse?: mainParse,
arrayParse?: {
maxRecursiveCalls?: number,
} & mainParse,
objectParse?: {
ifDuplicateKey?: {
rewrite?: boolean,
warn?: boolean,
},
maxRecursiveCalls?: number,
} & mainParse,
}
Required to display the help menu.
Array of flags that will display the help menu.
Example:
fargv({
help: {
status: true,
flagsToCall: ["h", "help", "HELP", "otherHelpAlias"]
}
})
Status that tells fargv whether to show the help menu.
Text of the main usage section.
Text of the main description section.
Additional text that is displayed at the end. Can be used as a custom help menu.
Responsible for displaying help about commands.
Responsible for displaying help about flags.
Responsible for displaying help about a specific command that is passed to the only one.
Responsible for displaying help about a specific flag that is passed to the only one.
Responsible for displaying examples in the main section of the help menu. It can take the values "commands" and "flags" to display examples in these sections.
Responsible for showing examples for a specific flag or command in the help menu. It can take the values "commands" and "flags" to display examples in these sections.
Answers - whether to end the process after displaying the help menu.
Object of commands that parameters will be read from when creating the help menu.
Example:
fargv({
help: {
status: true,
commands: {
someCommand: {
a: "aliasOfSomeCommand",
desc: "some description of someCommand",
usage: "someCommand [someOther]",
flags: ["a", "b"],
examples: ["someCommand someSubCommand", "someCommand someSecondSubCommand"]
},
someSecondCommand: {
desc: "some description of someSecondCommand"
}
}
}
})
Array of aliases for this command. It can be a string that turns into an array during parsing.
Text for the description section in this command.
Text for the usage section in this command.
Flags that this command is associated with and that will be shown next.
An array of examples consisting of strings that will be shown in the examples section. Can be a string.
Object of flags that parameters will be read from when creating the help menu.
Text for the description section in this flag.
If Boolean true - shows [required], if string - shows [required: text].
A string that shows text like this in the flags section: [deprecated: text].
If true, it shows [must be empty], if false, it shows [must be with value], otherwise it doesn't show anything in the flags section.
Shows the passed type in the flags section. Must be one of the following values: "string" | "number" | "array" | "object" | "bigint" | "boolean".
Array of aliases for this flag. It can be a string that turns into an array during parsing.
An array of examples consisting of strings that will be shown in the examples section. Can be a string.
An array of commands that should include arrays containing the command name, the command handler, and an array of command aliases.
Example:
fargv({
commands: [
["commandName", function (){}, []],
["secondCommand", state => {}, []]
]
})
A separate handler for any commands that will be called if no other handlers were called or if the alwaysCallSeparateCommandHanler option is true.
If true, stops calling other possible command handlers. The default value is true.
If true, it calls separateCommandHandler in any case. By default, it is false.
If true, the second argument to the command handler will pass an array of the remaining commands. Otherwise, the spread format will work. By default, it is false.
An array of strings that can be used as an alternative parsing of your own arguments. Must accept syntax-correct arguments like equal-sign flags.
Example:
fargv({
customArgv: [
"--flagName=flagValue",
"--secondFlagName=secondFlagValue"
]
})
An object where the property name is a flag to which default values can be applied, and the property value is an array, where the first element is the default value itself, and the second is an array of aliases for this flag.
Example:
fargv({
defaultArgv: {
someFlagName: ["someDefaultFlagValue", ["someFlagAlias"]]
}
})
An array of string flags which are required to be transferred in this process. If any of the flags are not present, regardless of the throwInsteadWarns option throws an exception of the type "required flags are missing".
Example:
fargv({
demandFlags: ["a", "b"]
})
Same as demandFlags, but given the missing from the parsing of the flags. We recommend using this option if some flags were excluded from the returned object using excludeFlags, but need to be passed to this process.
Array of string flags that should be skipped and not returned in the flag sections.
Example:
fargv({
excludeFlags: ["someFlag", "someOtherFlag"]
})
Array of string flags that don't need to be parsed. Important note - defaultNoneValue and defaultArgv take priority over this option, respectively, the default values will be set if the flag does not have a value.
Same as noParseFlags, but excludes the priority of defaultNoneValue (without defaultArgv). If the flag has no value, the default value is assigned from defaultArgv or undefined.
A string or array of strings that tells fargv in which format to return a particular property. If a string or array with a single element is passed, it returns a property that is equal to the passed argument (if the property is missing, an empty object is returned). If an array of strings is passed, a filtered object is returned, where the properties are the same as the array elements.
Example:
fargv({
returnFilter: ["flags", "commands"]
})
Logical option. If true, it remembers the path to the node in the _ property of the returned object. By default, false.
Logical option. If true, it remembers the path to the main executable file in the _ property of the returned object. By default, true.
Logical option. If true, remembers the name of the main executable file in the _ property of the returned object. By default, true.
Logical option. If true, it remembers all errors that occur during parsing in the "warns" array property. By default, false.
Logical option. If true, it shows warnings that occur during parsing using the console.warn . By default, true.
User-defined function, if set - fargv tells it the details of the warning.
Logical option. If true, throws an exception instead of storing or logging the error during parsing. By default, it is false.
Logical option. If true, parses flags without the value passed through the equal sign. The default value is true.
Logical option. If true, it doesn't matter how many characters that say that this argument is a flag is needed. The default value is true.
Logical option. If true, fargv considers that flags are passed only through the Latin alphabet of any case. The default value is true.
The symbol that will be used for splitting arrays and objects in parsing. The default value is , .
Example with , :
const argv = fargv({
returnFilter: "flags",
allParse: true
});
console.log(argv);
$ node ./exampleWithComma.js -a="[some, value, v, true]"
{ a: [ 'some', 'value', 'v', true ] }
Example with # :
const argv = fargv({
returnFilter: "flags",
allParse: true,
defaultCommaSplitSym: "#",
});
console.log(argv);
$ node ./exampleWithHash.js -a="[some# value, v# true]"
{ a: [ 'some', 'value, v', true ] }
This is an option for arrays and objects. The default value is true.
Functionality in an array: if true, allows spaces between delimiters to be an independent value. Otherwise, the value is taken from arrayParse.defaultNoneValue.
Example with true value:
const argv = fargv({
returnFilter: "flags",
allParse: true,
allowSpacesAsValues: true,
});
console.log(argv);
$ node ./allowSpacesAsValuesTrue.js -a="[some, value, v, ,true]"
{ a: [ 'some', 'value', 'v', ' ', true ] }
Example with false value:
const argv = fargv({
returnFilter: "flags",
allParse: true,
allowSpacesAsValues: false,
});
console.log(argv);
$ node ./allowSpacesAsValuesFalse.js -a="[some, value, v, ,true]"
{ a: [ 'some', 'value', 'v', null, true ] }
Functionality in the object - depends on the useDnvForFirstSpaceOP option.
Logical option for parsing object properties. The default value is true.
Answers whether to apply objectParse.defaultNoneValue to possible properties consisting of a single space.
Allows a space in a possible object property only if the allowSpacesAsValues option is set to true and useDnvForFirstSpaceOP is false.
Example:
const argv = fargv.objectParse({
defaultNoneValue: 4,
}).init({
returnFilter: "flags",
allParse: true,
allowSpacesAsValues: true,
useDnvForFirstSpaceOP: false,
}, true);
console.log(argv);
$ node ./useDnvForFirstSpaceOP.js -f="{a: 1, b: , c: 3, d: ,}"
{ f: { a: 1, b: ' ', c: 3, d: 4 } }
The example shows that the property b was assigned the value ' ', and d got the value 4. This happened because b had one space, and d had 2 spaces.
Logical option. It has the same purpose as noParseFlags, but it can be set for all flags at once. By default, it is false.
Logical option. It has the same purpose as noParseNoDefaultFlags, but it can be set for all flags at once. By default, it is false.
Logical option. If true - sets true on all properties in mainParse, arrayParse, and objectParse, which allows you to parse absolutely everything. By default, it is false.
The default value that a flag should get that doesn't have a value for one reason or another (for example, passing the flag as follows: --flag, --flag= ). By default, null.
Logical option. If true, it parses everything within the main level(without affecting the parsing settings for arrays and objects). By default, it is false.
Logical option. If true, sets the values of properties mainParse.boolean, mainParse.array and mainParse.object to true. By default, false.
Logical option. If true, sets the values of properties mainParse.null, mainParse.undefined, mainParse.NaN and mainParse.Infinity to true. By default, false.
Logical option. If true, values with underscores are parsed as numbers in accordance with the new standard. By default, it is false.
Logical option. If true, the values will try to be parsed as numbers. By default, it is true.
Logical option. If true, the values will try to be parsed as BigInt. By default, it is false.
Logical option. If true, the values will try to be parsed as Boolean values (true or false). By default, it is false.
Logical option. If true, the values will try to be parsed as arrays. By default, it is false.
Logical option. If true, the values will try to be parsed as objects. By default, it is false.
Logical option. If true and the flag value is null, it equates the value to null. By default, it is false.
Logical option. If true and the flag value is undefined, it equates the value to undefined. By default, it is false.
Logical option. If true and the flag value is NaN, it equates the value to NaN. By default, it is false.
Logical option. If true and the flag value is Infinity, it equates the value to Infinity. By default, it is false.
The number responsible for the number of maximum recursions, if, for example, an array is parsed in an array. The default value is 10.
arrayParse takes over from mainParse properties that regulate parsing values, but only now in the area of parsing array elements.
The only difference here is in the default values. Instead of false, the following properties have true: boolean, null, undefined.
Answers what to do if duplicate properties are found during object parsing.
Logical option. If true, it enters a new value in an existing property. The default value is true.
Logical option. If true, it indicates whether fargv should use errorHandler in the current situation. The default value is true.
The number responsible for the number of maximum recursions, if, for example, an object is parsed in an object. The default value is 10.
objectParse takes over from mainParse properties that regulate parsing values, but only now in the area of parsing object elements.
The only difference here is in the default values. Instead of false, the following properties have true: boolean, null, undefined.
Sets parsing options in fargvWrapper._options. By default, a merge is performed if the redefine argument is not passed. Can be called with the 1st "reset" argument, which will set fargvWrapper._options to null.
If fargvWrapper._options is not an object, this method will set the object.
Resets the option passed in the option argument
Resets all options.
Sets the commands option. If only one function is passed as a single argument, the separateCommandHandler option is set.
Interface:
interface staticFargvCommand {
command: "reset" | Function | string | string[],
handler: (state: fargvReturns, ...nextCommands: string[]) => void,
help?: {
[a | alias | aliases]?: array<string> | string,
desc?: string,
usage?: string,
flags?: array<string> | string,
examples?: array<string> | string,
}
}
Sets the separateCommandHandler and/or alwaysCallSeparateCommandHanler option.
Sets the help.flags[optionName] option.
Interface:
interface optionConfig {
desc?: string,
required?: boolean | string,
deprecated?: boolean | string,
empty?: boolean,
type?: "string" | "number" | "array" | "object" | "bigint" | "boolean",
[a | alias | aliases]?: array<string> | string,
examples?: array<string> | string,
}
interface staticSetOptionFlag {
optionName: string,
optionConfig: optionConfig
}
The same as fargv.optionFlag(version, optionConfig) with some additions.
Sets the help.commands[commandName] option.
Interface:
interface commandHelpConfig {
[a | alias | aliases]?: array<string> | string,
desc?: string,
usage?: string,
flags?: array<string> | string,
examples?: array<string> | string,
}
interface staticSetOptionCommand {
commandName: string,
commandHelpConfig: commandHelpConfig
}
Sets the help object with properties.
Interface:
interface staticIntegrateHelp {
flagsToCall: array | string,
concatFlagsToCall: true | boolean,
mainUsage: string,
mainDesc: string,
mainCustomEndText: string,
showMainCommands: boolean,
showMainFlags: boolean,
showForSpecificCommand: boolean,
showForSpecificFlag: boolean,
showExamples: boolean | "commands" | "flags",
showExamplesForSpecific: boolean | "commands" | "flags",
exit: boolean,
commands: commandHelpConfig,
flags: optionConfig,
}
Sets the defaultArgv option.
Interface:
interface staticSetDefaultArgv {
objectOfValues: "reset" | {
[key: string] : any | {
_options: {
[value | argValue | v]: [undefined, "$notFill"] | any,
[alias | a | aliases]: string | string[],
}
} | ["$fargvSetDefault", [undefined, "$notFill"] | any, string | string[]]
},
redefine: any
}
Sets the customArgv option.
Interface:
interface staticSetCustomArgv {
customArgv: [
...array<string, string>
]
}
Sets the customArgv option by generating (see fargv.generate interface).
Sets the customArgv option by generating from an object (see fargv.generateFromObject interface).
Sets the demandFlags or demandWithSkippedFlags option.
Unsets the demandFlags or demandWithSkippedFlags option.
Sets the excludeFlags option.
Sets the noParse or noParseNoDefault option.
Sets the noParseFlags or noParseNoDefaultFlags option.
Sets the allParse option.
Sets the returnFilter option.
Sets the following options: rememberExecNodePath, rememberExecFilePath, rememberExecFileBasename.
Interface:
interface staticSetRemember {
[file | fileName | execFileBasename]?: boolean,
[filePath | execFilePath]?: boolean,
[node | nodePath | execNodePath]?: boolean,
}
Sets the following options: rememberWarns, showWarns, throwInsteadWarns, parseWarn.
Interface:
interface staticSetWarns {
remember?: boolean,
show?: boolean,
["throw" | throwInsteadWarns]?: boolean,
parser: Function,
}
Sets the arrayParse option.
Sets the objectParse option.
Returns the current state based on the passed about argument.
Returns a string with special syntax based on an array.
Returns a string with special syntax based on an object.
Returns an array based on a string with special fargv syntax.
Returns an object based on a string with special fargv syntax.
Checks whether a string can be an array using the fargv syntax.
Checks whether a string can be an object using the fargv syntax.
Returns the same as fargv.strIsArray, but the check is more strict.
Returns the same as fargv.strIsObject, but the check is more strict.
Transforms arrays, objects, and other values into a string-specific syntax that allows fargv to parse these as values.
Interface:
interface generateElementStructure {
[name | argName | n]: string,
[value | argValue | v]: any,
[flag | f | flagDC]: number,
[pre | p | prePush]: (res: string) => string,
[wes | withoutES | withoutEqualSym]: boolean,
}
interface generate_OptionsStructure {
useSpacesAsDelimiters: boolean | {
array: boolean,
object: boolean,
}
}
interface generateOptionsStructure {
_options: generate_OptionsStructure
}
type generateElementOrOptions = generateElementStructure | generateOptionsStructure;
function generate(argName: generateElementOrOptions, argValue: generateElementOrOptions, ...args: generateElementOrOptions[]): string {}
function generate(argName: generateElementOrOptions, argValue: generateElementOrOptions): string {}
function generate(argValue: generateElementOrOptions): string {}
function generate(argValue: array<generateElementOrOptions>): string {}
function generate(argName: string, argValue: any, options: generateOptionsStructure | generate_OptionsStructure): string {}
function generate(argName: string, argValue: any): string {}
The same as fargv.generate only with a different interface.
Interface:
interface generateFromObjectElementStructure {
[key: string]: any
}
interface generateFromObjectOptionsStructure {
_options: generate_OptionsStructure & {
_more: {
_throwInsteadWarns: false | boolean,
before: {
[key: string]: generate_OptionsStructure
},
after: {
[key: string]: generate_OptionsStructure
}
}
}
[key: string]: {
[flag | f | flagDC]: number,
[pre | p | prePush]: (res: string) => string,
[wes | withoutES | withoutEqualSym]: boolean,
}
}
function generateFromObject(objectOfValues: generateFromObjectElementStructure, objectOfConfigs?: generateFromObjectOptionsStructure): string {}
function generateFromObject(getParsedArgs: true, objectOfValues: generateFromObjectElementStructure, objectOfConfigs?: generateFromObjectOptionsStructure): array<generateElementOrOptions> {}
The initialization parsing. If nothing is passed, it is based on fargvWrapper._options. If an object is passed without a subsequent true argument, it is based solely on this object. If the first argument is passed an object, and the second is true - merges the received object with fargvWrapper._options and starts initialization.
Alias of fargv.returnFilter("flags").init(...arguments)
Alias of fargv.returnFilter("commands").init(...arguments)
Alias of fargv.returnFilter(["flags", "commands"]).init(...arguments)
Yandex Mail - vladimirvsevolodovi@yandex.ru
Github - https://github.com/StormExecute/
Github - https://github.com/StormExecute/fargv/
NPM - https://www.npmjs.com/package/fargv/
MIT - https://mit-license.org/