Skip to content

Instantly share code, notes, and snippets.

@tnhu
Forked from azproduction/LICENSE.txt
Created December 21, 2011 15:27
Show Gist options
  • Save tnhu/1506420 to your computer and use it in GitHub Desktop.
Save tnhu/1506420 to your computer and use it in GitHub Desktop.
Simple argv parser in 100 bytes

Simple argv parser in 100 bytes

Parses Unix (-pewpew, --pew-pew=value, --pewpew value) and Dos style (/x, /x value) argv strings

Input

"node server.js -h 0.0.0.0 -p 80 -s -a --vvvv --r-x /v 123 /x --debug-enabled=yes"

Output

{
  "h": "0.0.0.0",
  "p": "80",
  "s": true,
  "a": true,
  "vvvv": true,
  "r-x": true,
  "v": 123,
  "x": true,
  "debug-enabled": "yes"
}

Demo: http://jsfiddle.net/p3mc9/3/

Thx @maettig for help

function (
argv, // {String} argv
item, // argv item
result, // result hash
i // counter
){
result = {}; // reset
for(
argv = argv.split(/\s*\B[\/-]+([\w-]+)[\s=]*/), // use special regexp
// "node pewpew.js --p a -c -d" ~~magic~~>
// ["node pewpew.js", "p", "a", "c", "", "d", ""]
i = 1; // skip 1 item ("node pewpew.js")
item = argv[i++]; // while !eoargv
result[item] = argv[i++] || !0 // set value, default true
);
return result;
}
function(a,b,c,d){c={};for(a=a.split(/\s*\B[\/-]+([\w-]+)[\s=]*/),d=1;b=a[d++];c[b]=a[d++]||!0);return c}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Mikhail Davydov
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "argv_parser",
"description": "Simple argv parser: both unix and dos style",
"keywords": [
"argv",
"parser",
"unix",
"dos"
]
}
<!DOCTYPE html>
<title>argv_parser</title>
<div>Expected value: <b>{"h":"0.0.0.0","p":"80","s":true,"a":true,"vvvv":true,"r-x":true,"v":"123","x":true,"debug-enabled":"yes"}</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var argv = 'node server.js -h 0.0.0.0 -p 80 -s -a --vvvv --r-x /v 123 /x --debug-enabled=yes',
argv_parser = function(a,b,c,d){c={};for(a=a.split(/\s*\B[\/-]+([\w-]+)[\s=]*/),d=1;b=a[d++];c[b]=a[d++]||!0);return c};
document.getElementById("ret").innerHTML = JSON.stringify(argv_parser(argv));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment