Skip to content

Instantly share code, notes, and snippets.

@pbnj
Last active September 13, 2018 20:41
Show Gist options
  • Save pbnj/3a57f2e0195ae2404c0a to your computer and use it in GitHub Desktop.
Save pbnj/3a57f2e0195ae2404c0a to your computer and use it in GitHub Desktop.
Demo Command-Line Interface (CLI) Application
#!/usr/bin/env node
'use strict';
/**
* Require dependencies
*
*/
const program = require('commander'),
chalk = require("chalk"),
exec = require('child_process').exec,
pkg = require('./package.json');
/**
* list function definition
*
*/
let list = (directory,options) => {
const cmd = 'ls';
let params = [];
if (options.all) params.push("a");
if (options.long) params.push("l");
let parameterizedCommand = params.length
? cmd + ' -' + params.join('')
: cmd ;
if (directory) parameterizedCommand += ' ' + directory ;
let output = (error, stdout, stderr) => {
if (error) console.log(chalk.red.bold.underline("exec error:") + error);
if (stdout) console.log(chalk.green.bold.underline("Result:") + stdout);
if (stderr) console.log(chalk.red("Error: ") + stderr);
};
exec(parameterizedCommand,output);
};
program
.version(pkg.version)
.command('list [directory]')
.option('-a, --all', 'List all')
.option('-l, --long','Long list format')
.action(list);
program.parse(process.argv);
// if program was called with no arguments, show help.
if (program.args.length === 0) program.help();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment