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

  • By
    9 Mind-Blowing Canvas Demos

    The <canvas> element has been a revelation for the visual experts among our ranks.  Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead.  Here are nine unbelievable canvas demos that...

  • By
    Designing for Simplicity

    Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...

Incredible Demos

  • By
    The Simple Intro to SVG Animation

    This article serves as a first step toward mastering SVG element animation. Included within are links to key resources for diving deeper, so bookmark this page and refer back to it throughout your journey toward SVG mastery. An SVG element is a special type of DOM element...

  • By
    Submit Button Enabling

    "Enabling" you ask? Yes. We all know how to disable the submit upon form submission and the reasons for doing so, but what about re-enabling the submit button after an allotted amount of time. After all, what if the user presses the "stop"...


  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!