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
    An Interview with Eric Meyer

    Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer...

  • By
    Animated 3D Flipping Menu with CSS

    CSS animations aren't just for basic fades or sliding elements anymore -- CSS animations are capable of much more.  I've showed you how you can create an exploding logo (applied with JavaScript, but all animation is CSS), an animated Photo Stack, a sweet...

Incredible Demos

  • By
    CSS Kwicks

    One of the effects that made me excited about client side and JavaScript was the Kwicks effect.  Take a list of items and react to them accordingly when hovered.  Simple, sweet.  The effect was originally created with JavaScript but come five years later, our...

  • By
    Creating the Treehouse Frog Animation

    Before we start, I want to say thank you to David for giving me this awesome opportunity to share this experience with you guys and say that I'm really flattered. I think that CSS animations are really great. When I first learned how CSS...


  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!