Date Archives

August 2020

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(`${} 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.