stdio

Standard input/output management module for NodeJS

View the Project on GitHub sgmonda/stdio

Installation

To install the most recent release from npm, run:

npm install stdio

Usage

You can do some things with this module:

Parsing UNIX-like command-line options

With stdio it is very easy to add suport for command-line options to a NodeJS program. There is a function called getopt() (like GNU utility) very easy to use. Imagine you have a script which may receive the name and age of an user, if he is redhead or not, and finally a folder with her files:

var stdio = require('stdio');

var options = stdio.getopt({
    'name': {description: 'User name', mandatory: true, args: 1},
    'surname': {description: 'User surname', args: 1},
    'age': {key: 'a', description: 'User age', args: 1},
    'redhead': {key: 'r', description: 'If he is redhead'}
});

Now, if you run your program with the following command:

node yourscript.js --name 'Rick' -r --age 33 /path/to/astley

Then the options object returned by getopt() will be as follows:

{
    'name': 'Rick',
    'redhead': true,
    'age': '33',
    'args': ['/path/to/astley']
}

So you can perform checks and use provided data however you want:

console.log('Your name is %s', options.name);
if (options.redhead) {
    console.log('You are redhead!');
}

Easy, isn't it?

Print usage

Now try to run you program adding a non-specified option, like -x for instance. What happens?

Unknown option: -k
USAGE: node preuba.js [OPTIONS] 
  --name < ARG1 >        User name (mandatory)
  --surname < ARG1 >     User surname
  -a, --age < ARG1 >     User age
  -r, --redhead          If he is redhead

It is cool!

The same info, with a proper error message, is shown if you forget to specify a mandatory option, or if you don't specify some required argument of an option.

You can print this usage info manually, too:

options.printHelp()

Read standard input at once

If you want to get the whole standard input at once, stdio lets you write the following:

var stdio = require('stdio');
stdio.read(function(data){
    console.log(data);
});

You can use it for small input files. It cannot be easier.

Prompt questions

This simple code:

var stdio = require('stdio');
stdio.question('Is this a question?', ['y', 'n'], function (err, answer) {
    // Use answer here
});

will show the provided question in the terminal, waiting user's answer:

Is this a question? [y/n]: