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
    Being a Dev Dad

    I get asked loads of questions every day but I'm always surprised that they're rarely questions about code or even tech -- many of the questions I get are more about non-dev stuff like what my office is like, what software I use, and oftentimes...

  • By
    CSS Animations Between Media Queries

    CSS animations are right up there with sliced bread. CSS animations are efficient because they can be hardware accelerated, they require no JavaScript overhead, and they are composed of very little CSS code. Quite often we add CSS transforms to elements via CSS during...

Incredible Demos

  • By
    Parallax Sound Waves Animating on Scroll

    Scrolling animations are fun. They are fun to create and fun to use. If you are tired of bootstrapping you might find playing with scrolling animations as a nice juicy refreshment in your dry front-end development career. Let's have a look how to create animating...

  • By
    Telephone Link Protocol

    We've always been able to create links with protocols other than the usual HTTP, like mailto, skype, irc ,and more;  they're an excellent convenience to visitors.  With mobile phone browsers having become infinitely more usable, we can now extend that convenience to phone numbers: The tel...

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!