argisanunopinionated,no-frillsCLIargumentparser.
InstallationnpminstallargUsagearg()takeseither1or2arguments:
Commandlinespecificationobject(seebelow)Parseoptions(Optional,defaultsto{permissive:false,argv:process.argv.slice(2),stopAtPositional:false})Itreturnsanobjectwithanyvaluespresentonthecommand-line(missingoptionsarethusmissingfromtheresultingobject).Argperformsnovalidation/requirementchecking-weleavethatuptotheapplication.
Allparametersthataren'tconsumedbyoptions(commonlyreferredtoas"extra"parameters)areaddedtoresult._,whichisalwaysanarray(evenifnoextraparametersarepassed,inwhichcaseanemptyarrayisreturned).
constarg=require('arg');//`options`isanoptionalparameterconstargs=arg(spec,(options={permissive:false,argv:process.argv.slice(2)}));Forexample:
$node./hello.js--verbose-vvv--port=1234-n'Myname'foobar--tagqux--tag=qix----foobar//hello.jsconstarg=require('arg');constargs=arg({//Types'--help':Boolean,'--version':Boolean,'--verbose':arg.COUNT,//Countsthenumberoftimes--verboseispassed'--port':Number,//--port<number>or--port=<number>'--name':String,//--name<string>or--name=<string>'--tag':[String],//--tag<string>or--tag=<string>//Aliases'-v':'--verbose','-n':'--name',//-n<string>;resultisstoredin--name'--label':'--name'//--label<string>or--label=<string>;//resultisstoredin--name});console.log(args);/*{_:["foo","bar","--foobar"],'--port':1234,'--verbose':4,'--name':"Myname",'--tag':["qux","qix"]}*/Thevaluesforeachkey=>valuepairiseitheratype(functionor[function])orastring(indicatinganalias).
Inthecaseofafunction,thestringvalueoftheargument'svalueispassedtoit,andthereturnvalueisusedastheultimatevalue.
Inthecaseofanarray,theonlyelementmustbeatypefunction.Arraytypesindicatethattheargumentmaybepassedmultipletimes,andassuchtheresultingvalueinthereturnedobjectisanarraywithallofthevaluesthatwerepassedusingthespecifiedflag.
Inthecaseofastring,analiasisestablished.Ifaflagispassedthatmatchesthekey,thenthevalueissubstitutedinitsplace.
Typefunctionsarepassedthreearguments:
Theparametervalue(alwaysastring)Theparametername(e.g.--label)Thepreviousvalueforthedestination(usefulforreduce-likeoperationsorforsupporting-vmultipletimes,etc.)Thismeansthebuilt-inString,Number,andBooleantypeconstructors"justwork"astypefunctions.
NotethatBooleanand[Boolean]havespecialtreatment-anoptionargumentisnotconsumedorpassed,butinsteadtrueisreturned.Theseoptionsarecalled"flags".
Forcustomhandlersthatwishtobehaveasflags,youmaypassthefunctionthrougharg.flag():
constarg=require('arg');constargv=['--foo','bar','-ff','baz','--foo','--foo','qux','-fff','qix'];functionmyHandler(value,argName,previousValue){/*`value`isalways`true`*/return'na'+(previousValue||'batman!');}constargs=arg({'--foo':arg.flag(myHandler),'-f':'--foo'},{argv});console.log(args);/*{_:['bar','baz','qux','qix'],'--foo':'nanananananananabatman!'}*/Aswell,argsuppliesahelperargumenthandlercalledarg.COUNT,whichequivalenttoa[Boolean]argument's.lengthproperty-effectivelycountingthenumberoftimesthebooleanflag,denotedbythekey,ispassedonthecommandline..Forexample,thisishowyoucouldimplementssh'smultiplelevelsofverbosity(-vvvvbeingthemostverbose).
constarg=require('arg');constargv=['-AAAA','-BBBB'];constargs=arg({'-A':arg.COUNT,'-B':[Boolean]},{argv});console.log(args);/*{_:[],'-A':4,'-B':[true,true,true,true]}*/OptionsIfasecondparameterisspecifiedandisanobject,itspecifiesparsingoptionstomodifythebehaviorofarg().
argvIfyouhavealreadyslicedorgeneratedanumberofrawargumentstobeparsed(asopposedtolettingargslicethemfromprocess.argv)youmayspecifythemintheargvoption.
Forexample:
constargs=arg({'--foo':String},{argv:['hello','--foo','world']});resultsin:
constargs={_:['hello'],'--foo':'world'};permissiveWhenpermissivesettotrue,argwillpushanyunknownargumentsontothe"extra"argumentarray(result._)insteadofthrowinganerroraboutanunknownflag.
Forexample:
constarg=require('arg');constargv=['--foo','hello','--qux','qix','--bar','12345','helloagain'];constargs=arg({'--foo':String,'--bar':Number},{argv,permissive:true});resultsin:
constargs={_:['--qux','qix','helloagain'],'--foo':'hello','--bar':12345};stopAtPositionalWhenstopAtPositionalissettotrue,argwillhaltparsingatthefirstpositionalargument.
Forexample:
constarg=require('arg');constargv=['--foo','hello','--bar'];constargs=arg({'--foo':Boolean,'--bar':Boolean},{argv,stopAtPositional:true});resultsin:
constargs={_:['hello','--bar'],'--foo':true};ErrorsSomeerrorsthatargthrowsprovidea.codepropertyinordertoaidinrecoveringfromusererror,ortodifferentiatebetweenusererroranddevelopererror(bug).
ARG_UNKNOWN_OPTIONIfanunknownoption(notdefinedinthespecobject)ispassed,anerrorwithcodeARG_UNKNOWN_OPTIONwillbethrown:
//cli.jstry{require('arg')({'--hi':String});}catch(err){if(err.code==='ARG_UNKNOWN_OPTION'){console.log(err.message);}else{throwerr;}}nodecli.js--extraneoustrueUnknownorunexpectedoption:--extraneousFAQAfewquestionsandanswersthathavebeenaskedbefore:
HowdoIrequireanargumentwitharg?Dotheassertionyourself,suchas:
constargs=arg({'--name':String});if(!args['--name'])thrownewError('missingrequiredargument:--name');LicenseReleasedundertheMITLicense.
评论