Node – Get Named Command Line Arguments
I am writing a small command line utility using Node and needed to get named arguments from the command line. A quick Google search led me down crazy complicated rabbit holes and (of course) a bunch of recommendations to just install npm modules.
There ain’t no way I’m installing an npm module to READ COMMAND LINE ARGUMENTS!
So I wrote a tiny function that gets command line arguments and turns them into an object. 10 lines is all you need in ES6.
function getArgs() {
const args = process.argv.slice(2);
let params = {};
args.forEach(a => {
const nameValue = a.split("=");
params[nameValue[0]] = nameValue[1];
});
return params;
}
Easy enough. Now if I call the script from the command line like this:
node myapp.js arg1=foo arg2=bar
I can transform the arguments to an object by calling:
const args = getArgs();
Which will give me the following object:
{
arg1: "foo",
arg2: "bar"
}
So now I can just do this:
// called using node myapp.js name=nick role="master of node"
const args = getArgs();
console.log(`${args.name} is the ${args.role}`);
// which outputs "nick is the master of node"
I mean, that’s all there is to it. I’ll save my rant about the wasteland that is npm for another post.
10 lines, challenge accepted! Much harder to read though 😉
const getArgs = () => process.argv.slice(2).reduce((params, nextArg) => ({...params, [nextArg.split("=")[0]]: nextArg.split("=")[1]}), {});
By the way it wouldn’t let me click in the name field for some reason? Had to tab
🙂 And still no silly npm libraries required!