• Stars
    star
    255
  • Rank 159,160 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Craft command-line masterpieces in Node.js

nash

Craft command-line masterpieces

API

Install

npm install nash --save

Usage

var nash = require('nash');
var cli = nash();

cli.beforeAll(function () {
  
  // Run this before all commands
});

cli.flag('-p')
  .handler(function (value, done) {
    
    // Do something when this flag is triggered
    done();
  });

cli.command('list')
  .handler(function (data, flags, done) {
    
    // Do something here
    done();
  });

cli.run(process.argv, function (err) {

  // All done!
});

Cli

run(argv[, callback])

Run the cli app with the given arguments. Normally you'd pass in process.argv. The callback can be used to execute more code after everything has completed.

var nash = require('nash');
var cli = nash();

cli.command('some-command')
  .handler(function (data, flags, done) {
  
    console.log('Some Command');
    done();
  });
  
cli.run(process.argv, function () {
  
  // All done
});

command(name[, names, ...])

Create a command with the given name(s). Supports a single name, and array of names, or multiple names separated by commas as arguments to the command method. Returns an instance of Command.

var nash = require('nash');
var cli = nash();

cli.command('some-command')
  .handler(function (data, flags, done) {
  	
    // Do something here
    done();
  });

default(callback)

Declare a default command to run if no command is provided. This is useful for small cli apps that have no commands and do only one task. This inherits the same api as a normal command.

var nash = require('nash');
var cli = nash();

cli.default()
  .handler(function (data, flags, done) {
  
    // Do stuff here
    done();
  });

cli.run([]);

flag(name[, names, ...])

Create a flag with the given name(s). Supports a single name, and array of names, or multiple names separated by commas as arguments to the command method. Returns an instance of Flag.

var nash = require('nash');
var cli = nash();

cli.flag('-f')
  .handler(function (value, done) {
  
  	// Do something with this flag value
    done();
  });

beforeAll(callback[, callback, ...])

Add a function or functions to be called before any commands or flags are run. The callback is passed to arguments":

  • data - the values passed in from the the terminal.
  • flags - a key/value map of flags and their corresponding values
var nash = require('nash');
var cli = nash();

cli.beforeAll(function (data, flags, done) {

  // data === ['value']
  // flags === {f: 'flag-value'}
  done();
});

cli.command('some-command')
  .handler(function (data, flags, doen) {
  
    done();
  })
  .flag('-f')
    .handler(function (val, done) {
    
      done();
    });

// This is usually sent in via process.argv
cli.run(['', '', 'some-command', 'value', '-f', 'flag-value']); 

afterAll(callback[, callback, ...])

Does the same thing as beforeAll(), except runs the callbacks after all the commands and flags are run.

set(name, value)

Cli-level/app-level settings. Set the given name to the given `value

  • name - name of key. Name, can also be a key/value object of multiple values
  • value - value of name
var nash = require('nash');
var cli = nash();

cli.set('key', 'value');
cli.set({
  key1: 'value1',
  key2: 'value2'
});

get(name)

Cli-level/app-level getter for settings.

  • name - name of key to get

register(plugin(s), callback)

Register a plugin with your command-line application. This provides extensibility and modularity. See Plugins for more information.

Command

Running cli.command('name') creates an instance of the Command class with following methods available:

handler(callback)

The callback gets executed when the command is called. Any values passed in to the run method on the cli get passed into the callback. You must call the done() callback to pass execution back to the cli.

var nash = require('nash');
var cli = nash();


// Sync mode
cli.command('some-command')
  .handler(function (data, flags, done) {

    // value === 'value'
    done();
  });

// Usually passed process.argv
cli.run(['', '', 'some-command', 'value']);

task(name[, name, ...])

Creates a sub task of the command. This is similar to the command tasks that the Heroku toolbelt has. This creates a command that looks like command:task when running. Calling task() returns and instance of Command.

var nash = require('nash');
var cli = nash();

cli.command('command')
  .task('task', 'tsk')
  .handler(function (data, flags, done) {
  	
    // Do something here
    done();
  });
  
cli.run(['', '', 'command:task']);

flag(name[, name, ...])

Creates a command-specific flag that only runs for that command. Returns an instance of Flag.

var nash = require('nash');
var cli = nash();

cli.command('command')
  .flag('-f', '--flag')
  .handler(function (value, done) {
  
    // Do something here
    done();
  });

cli.run(['', '', 'command', '-f']);

before(callback[, callback, ...])

Add a function or functions to be called before the command and the command's flags are run. This has the same callback signature as Cli's beforeAll()

after(callback[, callback, ...])

This is the same as the before() method, except this is called after the command and all it's flags run.

name(name[, name, ...])

Add more names to the command. Helpful if you want aliases or mispellings to trigger the command. This can also be used to get all the aliases for a given command.

var nash = require('nash');
var cli = nash();

cli.command('command')
  .name('cmd', 'commnd')

Flag

Running cli.flag('name') or cli.command('name').flag('name') creates an instance of the Flag class. If created under a command, the flag only runs with that command. The Flag class has the following methods available:

handler(callback)

The callback gets executed when the flag is called. Any values passed in to the run method on the cli get passed into the callback. The done() callback must be called to pass execution back to the cli.

var nash = require('nash');
var cli = nash();


// Sync mode
cli.command('some-command')
  .flag('-f')
  .handler(function (value, done) {
  
    // Do something here
    done();
  });


// Usually passed process.argv
cli.run(['', '', 'some-command', '-f']);

override()

If no value or a value of true is passed in, this command specific flag will override the cli/global flag. If set to false or not called, the flag will run in series after the cli/global flag.

var nash = require('nash');
var cli = nash();


cli.flag('-f')
	.handler(function (value, done) {
    
    done():
  });

cli.command('some-command')
  .flag('-f')
  .override()
  .handler(function (value, done) {
  
    // Only this flag runs for -f
    done();
  });
  
cli.run(['', '', 'some-command', '-f']);

name(name[, name, ...])

Add more names to the flag. Helpful if you want aliases or mispellings to trigger the flag.

var nash = require('nash');
var cli = nash();

cli.command('command')
	.flag('-f')
	  .name('--flag', '--flaggling');

Plugins

Nash lets you register plugins via the register method on the cli object. This makes it easier to break up your app as it grows.

YOu can register an array of plugins or a single plugin. Each object used to register the plugin must contain a register key with the value being the plugin function. See below for examples.

Optionally, you can provide an options object to pass to each plugin.

Example of registering a plugin:

var nash = require('nash');
var myPlugin = require('my-plugin');
var cli = nash();

cli.register([{
  register: myPlugin,
  options: {
    key: 'value'
  }
}], function (err) {

  // Done loading plugins
});

Example plugin:

module.exports = function (cli, options, done) {
  
  cli.command('something')
    .handler(function (data, flags, done) {
      
      // Do something here
      done();
    });
  
  done();
};

Each plugin must export a function. This method is called and given the arguments:

  1. Cli object.
  2. Options you pass when registering the plugin.
  3. Callback. This must be called in order to complete the registration process

Run Tests

npm install
npm test

License

MIT

More Repositories

1

tiny-emitter

A tiny (less than 1k) event emitter library
JavaScript
928
star
2

pushstate-server

Static file server that works with HTML5 Pushstate.
JavaScript
421
star
3

immu

A TINY, fail-fast, lazy, immutable Javascript objects library.
JavaScript
356
star
4

tap-spec

Formatted TAP output like Mocha's spec reporter
JavaScript
285
star
5

awesome-js-drama

A collection of Javascript topics the just might spark the next revolt!
177
star
6

angular-linkify

Angular filter, directive, and service to linkify text.
JavaScript
82
star
7

contrast

Determine if the given hex color is light or dark. Helpful to determining foreground color against a background color.
JavaScript
60
star
8

angular-scrollto

Angular directive to scroll to element by selector.
JavaScript
54
star
9

express-boom

Boom response objects in Express
JavaScript
45
star
10

tonehunt

TypeScript
38
star
11

tap-dot

Formatted TAP output with dots ...
JavaScript
36
star
12

awesome-elm-metal

Awesome metal to listen to while coding Elm
36
star
13

angular-gist

AngularJS directive for embedding Github gists.
JavaScript
36
star
14

Injector

Node.js directory-independent dependency injection for apps and testing.
JavaScript
36
star
15

tapes

A more robust tap-producing test harness for node and browsers. Adds suites, beforeEach, afterEach, etc.
JavaScript
34
star
16

file-exists

Check if filepath exists and is a file
JavaScript
33
star
17

elm-css-normalize

A port of normalize.css for elm-css
Elm
30
star
18

bucket-zip

Download a directory from an Amazon S3 bucket as zip file.
JavaScript
25
star
19

tap-out

A different tap parser
JavaScript
23
star
20

tiny-trigger

Trigger cross-browser DOM events. Works with Browserify and as a standalone
JavaScript
22
star
21

reinstall

Reinstall package's node modules without cache
JavaScript
20
star
22

listenify

Partially applied DOM event listeners
JavaScript
17
star
23

lag

Functionally handle promises
JavaScript
16
star
24

httpify

Http in the browser and Node.js with no hassle
JavaScript
15
star
25

keyboard-combo

Handle keyboard key combinations with type safety in Elm
Elm
15
star
26

args-list

Extract method arguments names into array.
JavaScript
11
star
27

home-dir

Get home directory path on any platform
JavaScript
10
star
28

molten

A fixed-fluid, full-width web application css grid.
CSS
10
star
29

rapper

Compose wrappers around api RESTful endpoints (Browser/Angular/Node).
JavaScript
6
star
30

elm-starter

My way of getting started with an Elm app ... navigation and elm-css included
Elm
6
star
31

tessed

A more robust tap-producing, tape compatible, test harness for node and browsers. Namespacing, context passing, beforeEach, afterEach, etc ...
JavaScript
6
star
32

hex-to-rgb

Convert color hex value to rgb
JavaScript
5
star
33

deliver

Deliver local and remote static files
JavaScript
5
star
34

elm-css-reset

Port of Eric Meyer's famous CSS reset
Elm
5
star
35

tiny-element

A tiny DOM element selector.
JavaScript
5
star
36

content-length

Express/Connect middleware to calculate the response payload size
JavaScript
4
star
37

series

Compose a series of chainable async methods
JavaScript
4
star
38

lot

Chainable async utilities for collections and arrays.
JavaScript
4
star
39

tiny-dom-notifier

Get notified when a given DOM element is created or removed.
JavaScript
4
star
40

wilson.js

Wrapper for the Wilson Score Equation to calculate rank based on positive and negative impressions. -- (Lower bound of Wilson score confidence interval for a Bernoulli parameter)
JavaScript
4
star
41

tiny-dom

A tiny (less than 200 bytes) string to DOM element parser
JavaScript
3
star
42

pretty-print

Print formatted data to the the command line.
JavaScript
3
star
43

domy-bind

Two-way data binding for front-end Browserify code
JavaScript
3
star
44

as-array

Make any value an array. No dependencies.
JavaScript
3
star
45

zip-object

Create an object from from arrays of keys and values. (Inspired by lodash's _.zipObject)
JavaScript
3
star
46

pathetic

Get values by path-like keys
JavaScript
3
star
47

compare-semver

Compare semver versions to many other semver versions
JavaScript
3
star
48

cycle-where

Cycle.js router driver with less configuration, more map(), and more fun
JavaScript
3
star
49

domy-events

Map DOM events to DOM elements (optionally with delegation)
JavaScript
3
star
50

elm-html-template

A large amount of html elements for showcasing styles on a single page
Elm
2
star
51

noridsh

A Sublime Text 3 theme based of the Nord color palette
2
star
52

.eslintrc

My .eslintrc config
2
star
53

join-path

Join urls or system paths, even with undefined values.
JavaScript
2
star
54

mix-into

Mix objects into other objects
JavaScript
2
star
55

query-parse

Parse query strings to objects and objects to strings. Hides null or empty values.
JavaScript
2
star
56

bower-s3

Install bower packages directly to s3 buckets.
JavaScript
2
star
57

bucket-list

Get a file list from an Amazon S3 bucket.
JavaScript
2
star
58

focus-ui

Atom theme to focus
CSS
2
star
59

regular

A collection of Javascript regular expressions
JavaScript
2
star
60

domy

A collection of small modules that make the DOM more peaceful
2
star
61

jsun

Error catching JSON methods. Hides away the try/catch madness for parsing strings and stringifying JSON objects.
JavaScript
1
star
62

narrator

Build api wrappers around RESTful endpoints
JavaScript
1
star
63

firehose

AngularJS service for relational Firebase data.
1
star
64

streams-done

Get a callback when all streams have ended
JavaScript
1
star
65

stream-dir

Stream directories recursively in Node.
JavaScript
1
star
66

piston

A route/path storing and parsing engine.
JavaScript
1
star
67

drainer

Queue and drain an array of functions in series.
JavaScript
1
star
68

copy-files

Streaming file copier
JavaScript
1
star
69

mocksy

Mock Node.js http server for testing. Regurgitates the request object.
JavaScript
1
star
70

tiny-delegate

Event delegation for DOM events
JavaScript
1
star
71

toxic

Mutate keys and values in Javascript objects
JavaScript
1
star
72

shrub

Manipulate lists of files recursively in Node. Chainable API with a promise ending.
JavaScript
1
star
73

incoming

Express-like server request helpers
JavaScript
1
star
74

static-app

Files to get you started developing a static app
JavaScript
1
star
75

file-count

Get the number of files in the given directory
JavaScript
1
star
76

is-xhr

Determine if incoming request is an XHR request
JavaScript
1
star
77

way

Simple, Standalone/Connect/Express routes
JavaScript
1
star
78

client-ip

Get the client IP address of the current request
JavaScript
1
star
79

buffer-json-stream

Buffer streaming JSON
JavaScript
1
star
80

fs3

Handle S3 objects like Node's fs module.
1
star
81

globject

Get values by glob-like keys
JavaScript
1
star
82

lessw

Watch and compile less files
JavaScript
1
star
83

bucket-files

Stream all files for a given bucket directory on Amazon S3
JavaScript
1
star
84

ampersand-drawer-view

Ampersand view class for hamburger drawer-like layouts.
JavaScript
1
star
85

domy-router

PushState URL driven DOM element swapping. A router that uses css selectors to render route templates.
JavaScript
1
star
86

domy-insert

Insert any data type to the DOM
JavaScript
1
star
87

outerwidth

Get an element's outerwidth, including padding, borders, and margin
JavaScript
1
star
88

continue

JavaScript
1
star
89

route-params

Get parameters from a route with segments
JavaScript
1
star