forked from eveningkid/args-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.js
45 lines (34 loc) · 950 Bytes
/
parse.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
'use strict';
/*
Straight-forward node.js arguments parser
Author: eveningkid
License: Apache-2.0
*/
const ARGUMENT_SEPARATION_REGEX = /([^=\s]+)=?\s*(.*)/;
function Parse(argv) {
// Removing node/bin and called script name
argv = argv.slice(2);
const parsedArgs = {};
let argName, argValue;
argv.forEach(function (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;
parsedArgs[argName] = argValue;
});
return parsedArgs;
}
module.exports = Parse;