node-main
Provides useful tools for writing command line scripts. It also ensures that a block of code is only invoked when called directly (as in calling node script
). It will not call the block of code if the script has been required in another module (as in require('script')
).
Bare bones example:
#!/usr/bin/env node
require('main')(module).run(function($) {
$.cout('foo').exit();
});
Installation & Usage
npm install --save main
require('main')(module)
Once required, you can chain the functions below.
Note that the module
part is required. This is to properly allow nesting of modules. e.g.
script1
contains require('main')(module)
script2
requires script1
, and implements it's own require('main')(module)
.
We expect that when running script2
from the command line that it will only call the main function of script2
, and not call the main function of script1
.
For the time being, this is required until I or someone else figures out a way around it. Read the caching section of the Node Modules API for more information.
.usage(message)
An optional message to append to the top of flags that can describe how the script should be invoked, e.g.
Usage: ./script [flags] <posArg1> <posArg2>
Flags do not have to be specified in this string. Usage for flags are automatically generated based on the options provided and will appear after this usage message (see below).
.flags(options)
options
follows the optimist format for options, but groups them together, e.g.:
require('main')(module).flags({
f: { alias: 'flag', demand: true },
t: { alias: 'secondFlag' },
d: { demand: true },
})
.run(fn)
fn
is the callback that will be invoked when the script is ran directly from a terminal. It can take the following parameters:
fn(scriptTools)
scriptTools
is a helper that provides tools for working with the command line. See below for it's usage.
$
Script Tools
When invoking .run()
, you will have access to some useful tools in it's callback function. These tools ease repetitive tasks that come up when working with command line scripts.
In the documentation below, the $
symbol stands for the script tool helper function. Feel free to use whatever name you like for this variable.
$(positionOrFlag)
Allows easy access to positional arguments, or flag values.
./script --name Bill /path/to/file
$(0);
$('name');
$.help
A string holding the help message that was generated from the usage and any flags provided.
$.args
An array holding the positional arguments that this script was invoked with.
$.exit([exitCode])
Exits the running program with the specified exit code.
$.stringify(thing)
Converts some "thing" that is passed in to a string. If it's an object, it will attempt to call JSON.stringify
on it. If it's an instance of Error
it will attempt to get the message of said error.
$.stdin(callback)
Read from stdin in it's entirety, and return a string once finished in a callback. Do not use this if you are dealing with large amounts of data from stdin - look towards streaming solutions.
$.stdin(function(input) { $.out(input); });
Output Helpers
Output helpers print text to the window, and can be chained, e.g.
$.cerr('Something failed').exit(1);
$.out(something)
and $.cout(something)
Write something to standard output. $.out
uses process.stdout.write
and cout
uses console.log
.
$.err(something)
and $.cerr(something)
Write something to standard output. $.err
uses process.stderr.write
and $.cerr
uses console.error
.
$.assert
Helps with the checking basic things. If an assertion fails it will print the usage information followed by the reason the script failed and then exit with a status of 1. All assertions can be chained, e.g.
$.assert.argsLenEq(1).cout($(0)).exit();
$.assert.argsLen
Check for positional arguments length. There is a family of checks available for use:
$.assert.argsLen(length)
positional arguments equals length?$assert.argsLenGe(length)
args greater than or equal to length?$assert.argsLenGt(length)
args greater than length?$assert.argsLenLe(length)
args less than or equal to length?$assert.argsLenLt(length)
args less than length?
Example
To view more examples visit the examples
directory.
Refer to the following script as basic.js
#!/usr/bin/env node
exports.sentence = function(name, word1, word2) {
return name + ', ' + word1 + ' ' + word2 + '.';
};
require('main')(module)
.usage('Usage:\n node test.js [flags] <word1> <word2>')
.flags({
n: { alias: 'name', demand: true }
})
.run(function($) {
$.assert.argsLen(2);
var word0 = $(0), word1 = $(1);
var name = $('name');
var sentence = exports.sentence($('name'), word0, word1);
$.cout(sentence).exit();
});
Using the module from another script will not execute the code in main:
var basic = require('./basic');
console.log(basic.sentence('Nolan', 'sit', 'down'));
Running from the terminal ($? indicates exit status in bash):
> node basic.js --name Nolan sit down
Nolan, sit down.
> $?
0 (success)
> node basic.js
> $?
1 (failure)
Note
When installing, make sure to use the --save
option and/or specify the version in your package.json
dependencies. This package is undergoing some heavy changes at the moment and new versions may be radically different from previous releases. This type of business will stop once it reaches 0.1.0.