Get Node.js Command Line Arguments with yargs

By  on  

Using command line arguments within Node.js apps is par for the course, especially when you're like me and you use JavaScript to code tasks (instead of bash scripts).  Node.js provides process.argv but that doesn't provide a key: value object like you'd expect:

/*
	$ node myscript.js --key1=value1 --key2=value2
	[ 'node',
	  '/path/to/myscript.js',
	  '--key1=value1',
	  '--key2=value2' ]
*/

Bleh.  If you want to work with a sane API for command line arguments, use yargs:

// Get the yargs resource
var yargs = require('yargs').argv;

// Check for arguments
if(yargs.someKey === expectedValue) {
	// Do whatever
}

/*
	yargs = {
		key1: value1
		key2: value2
	};
*/

yargs provides a key:value object for arguments instead of the native process.argv mess.  No hassle, no fuss, just access to command line arguments with a logical API.  Happy noding!

Recent Features

  • By
    How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

  • By
    5 Awesome New Mozilla Technologies You’ve Never Heard Of

    My trip to Mozilla Summit 2013 was incredible.  I've spent so much time focusing on my project that I had lost sight of all of the great work Mozillians were putting out.  MozSummit provided the perfect reminder of how brilliant my colleagues are and how much...

Incredible Demos

  • By
    Build a Slick and Simple MooTools Accordion

    Last week I covered a smooth, subtle MooTools effect called Kwicks. Another great MooTools creation is the Accordion, which acts like...wait for it...an accordion! Now I've never been a huge Weird Al fan so this is as close to playing an accordion as...

  • By
    Image Manipulation with PHP and the GD Library

    Yeah, I'm a Photoshop wizard. I rock the selection tool. I crop like a farmer. I dominate the bucket tool. Hell, I even went as far as wielding the wizard wand selection tool once. ...OK I'm rubbish when it comes to Photoshop.

Discussion

  1. [pirateAccent]Yaaaarrrrrg!![/pirateAccent]

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!