CLI Tools in Node.js

SKGNode Meetup

Adonis K.

Front-end Developer at Goodvidio

adonisk.com

Let's get started

The structure

  • Options
  • Commands
  • Command Options

Options

  • Short (single character)
  • Long (spinal-case)
  • Can be Boolean or String
#short options
ls -a
ls -a -R
ls -aR

#long options
ls --all
ls --all --recursive
ls --version

#long options with values
ls --color=auto

examples

Commands

npm install
npm update
npm remove
npm search
npm test
npm publish
npm version

examples

Command Options

npm install --help
npm install -g grunt
npm install -S grunt
npm install --global grunt
npm install --save grunt
npm install --save-dev grunt

examples

Multiple Values

  • Must be the last part of the command
  • Can take multiple values (space separated)
  • Can only be the last!
# gzip multiple files
gzip file1 file2
# checksum multiple files
sum file1 file2 file3
# remove multiple directories
rmdir mydir yourdir deer

examples

Commander.js

node.js command-line interfaces made easy

github.com/tj/commander.js

Get Commander

npm install --save commander

Require it

cli = require('commander');

Creating an Option

cli.option('-v, --version', 'output the version number');

Creating a Command

cli
    .command('sort <list>')
    .description('returns the list sorted')
    .action(function (list) {
        console.log(sort(list));
    });

Adding Options to Commands

cli
    .command('sort <list>')
    .description('returns the list sorted')
    .option("--direction [direction]", "Which order to sort by [asc | desc]")
    .action(function (list) {
        if (options.direction !== 'desc') {
            console.log( sort(list, 'asc') );
        } else {
            console.log( sort(list, 'desc') );
        }
    });

Multiple values

cli
    .command('sum <value> [moreValues...]')
    .description('returns the sum of the values passed')
    .action(function (value, moreValues) {
        var result = parseInt(value, 10);

        moreValues.forEach(function (value) {
        	result += parseInt(value, 10);
        });

        console.log(result);
    });

package.json

{
    "preferGlobal": true,
    "bin": {
        "clitools": "index.js"
    }
}

Shebang

#!/usr/bin/env node

Source && npm install

  • https://github.com/skgnode/skgnode-clitools
  • npm install -g skgnode-clitools

More libraries

  • tkellen/node-liftoff
  • tjbarber/gnu-argv
  • sindresorhus/meow
  • substack/node-optimist
  • substack/minimist

Thanks You

Enjoy the Beer

CLI Tools in Node.js

By Adonis K.