Skip to content

Instantly share code, notes, and snippets.

@Lucbug
Created April 11, 2018 20:47
Show Gist options
  • Save Lucbug/b091f00ac46b7f2b2d58fc8115e11c20 to your computer and use it in GitHub Desktop.
Save Lucbug/b091f00ac46b7f2b2d58fc8115e11c20 to your computer and use it in GitHub Desktop.
Create an object containing argument values in Gulp
// 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);
@Lucbug
Copy link
Author

Lucbug commented Apr 11, 2018

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.

@Lucbug
Copy link
Author

Lucbug commented Apr 11, 2018

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