Created
April 11, 2018 20:47
-
-
Save Lucbug/b091f00ac46b7f2b2d58fc8115e11c20 to your computer and use it in GitHub Desktop.
Create an object containing argument values in Gulp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// fetch command line arguments | |
const arg = (argList => { | |
let arg = {}, a, opt, thisOpt, curOpt; | |
for (a = 0; a < argList.length; a++) { | |
thisOpt = argList[a].trim(); | |
opt = thisOpt.replace(/^\-+/, ''); | |
if (opt === thisOpt) { | |
// argument value | |
if (curOpt) arg[curOpt] = opt; | |
curOpt = null; | |
} | |
else { | |
// argument name | |
curOpt = opt; | |
arg[curOpt] = true; | |
} | |
} | |
return arg; | |
})(process.argv); |
When we run gulp task1 --a 123 --b "my string" --c, the arg object is set to:
{
"a": "123",
"b": "my string",
"c": true
}
We can, therefore, examine and use those values as required.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The function loops through the process.argv array. When it encounters a value preceded with one or more dashes, it creates a new named value in the arg object which is set to true. When it encounters a value without dashes, it sets the previous named value (if available) to that string.