reka-core-20240722· unknown
from LMArena Human Preference 100K
nodejs onelinesnippet function to parse args in format "script.js -arg1 value1 .."
- User
nodejs onelinesnippet function to parse args in format "script.js -arg1 value1 .."
- Assistant
Here's a one-liner Node.js function using
process.argvto parse command line arguments in the formatscript.js -arg1 value1 ...:javascriptconst parseArgs = (args) => Object.fromEntries(args.slice(2).reduce((acc, val, i) => { if (i % 2 === 0) acc[val.slice(2)] = args[i + 1]; return acc; }, {})); // Usage: const args = process.argv; const parsedArgs = parseArgs(args); console.log(parsedArgs);Explanation:
args.slice(2)skips the first two elements ofprocess.argvwhich arenodeand the script file path.reduceis used to iterate over the remaining arguments, pairing each option (-argX) with its corresponding value.val.slice(2)removes the leading-from the option name.Object.fromEntriesconverts the resulting array of key-value pairs into an object.
Example usage: Run your script from the command line like this:
bashnode script.js -arg1 value1 -arg2 value2The
parsedArgsobject will be:javascript{ arg1: 'value1', arg2: 'value2' }