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',
	  '--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

Incredible Demos

  • By
    Upload Photos to Flickr with PHP

    I have a bit of an obsession with uploading photos to different services thanks to Instagram. Instagram's iPhone app allows me to take photos and quickly filter them; once photo tinkering is complete, I can upload the photo to Instagram, Twitter, Facebook, and...

  • By
    Pure CSS Slide Up and Slide Down

    If I can avoid using JavaScript for element animations, I'm incredibly happy and driven to do so.  They're more efficient, don't require a JavaScript framework to manage steps, and they're more elegant.  One effect that is difficult to nail down with pure CSS is sliding up...


  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!