Initial Commit ...
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* XArgs Parser Module ...
|
||||
* a module for parsing args in node js cli apps ...
|
||||
*
|
||||
* Maintainer
|
||||
*
|
||||
* Hadi Khazaee Asl <https://saherelm.ir> (hadi_khazaee_asl@yahoo.com)
|
||||
*/
|
||||
|
||||
//
|
||||
//#region Variable/Constants ...
|
||||
const ARGUMENT_SEPARATION_REGEX = /([^=\s]+)[=\ ]?\s*(.*)/;
|
||||
//#endregion
|
||||
|
||||
//
|
||||
//#region Actions ...
|
||||
function parseArgs(argv) {
|
||||
//
|
||||
// Removing node/bin and called script name
|
||||
argv = argv.slice(2);
|
||||
|
||||
//
|
||||
const result = {};
|
||||
let argName;
|
||||
let argValue;
|
||||
|
||||
//
|
||||
if (
|
||||
argv === null
|
||||
|| argv === undefined
|
||||
|| argv.length === 0
|
||||
) {
|
||||
return result;
|
||||
}
|
||||
|
||||
//
|
||||
const argString = argv.join(" ");
|
||||
let matches = argString
|
||||
.match(ARGUMENT_SEPARATION_REGEX);
|
||||
matches.splice(0, 1);
|
||||
matches = matches
|
||||
.filter(m => m !== undefined && m !== "");
|
||||
|
||||
//
|
||||
matches.forEach(arg => {
|
||||
//
|
||||
// Separate argument for a key/value return
|
||||
arg = arg.match(ARGUMENT_SEPARATION_REGEX);
|
||||
arg.splice(0, 1);
|
||||
|
||||
//
|
||||
// Retrieve the argument name
|
||||
argName = arg[0];
|
||||
|
||||
//
|
||||
// Remove "--" or "-"
|
||||
if (argName.indexOf('-') === 0) {
|
||||
//
|
||||
argName = argName
|
||||
.slice(
|
||||
argName
|
||||
.slice(0, 2)
|
||||
.lastIndexOf('-') + 1
|
||||
);
|
||||
}
|
||||
|
||||
//
|
||||
// Parse argument value or set it to `true` if empty
|
||||
argValue =
|
||||
arg[1] !== ''
|
||||
? parseFloat(arg[1])
|
||||
.toString() === arg[1]
|
||||
? +arg[1]
|
||||
: arg[1]
|
||||
: true;
|
||||
|
||||
//
|
||||
result[argName] = argValue;
|
||||
});
|
||||
|
||||
//
|
||||
return result;
|
||||
}
|
||||
//#endregion
|
||||
|
||||
//
|
||||
//#region Exports ...
|
||||
module.exports = {
|
||||
parseArgs
|
||||
};
|
||||
//#endregion
|
||||
Reference in New Issue
Block a user