mhulse / node-boilerplate-cli

A simple boilerplate starting point for Node.js command line projects.
Apache License 2.0
18 stars 8 forks source link

Example of nested scripts with two yargs calls #21

Open mhulse opened 5 years ago

mhulse commented 5 years ago

This may not work exceptionally well if logic is more complex ... but, here's one quick way to do nested scripts:

// index.js
import yargs from 'yargs';

import pkg from '../package.json';
import utilities from './scripts/utilities';
import find from './scripts/find';

let argv = yargs
  .version(pkg.version)
  .usage(`Usage: $0 --script [name of script]`)
  .option('script', {
    description: 'Name of script to run (no extension).',
    type: 'string',
    demand: true,
  })
  .argv;

switch (argv.script) {

  case 'find':
    find.getOptions();
    break;

  default:
    utilities.o('log', `Script does not exist: ${argv.script}`.red.bold);
    utilities.exitGraceful();

}
// scripts/find.js

function getOptions() {

  let argv = yargs
    .version(pkg.version)
    .usage(`Usage: $0 -d [/path/to/directory/]`)
    .option('directory', {
      alias: [
        'd',
      ],
      description: 'A directory!',
      type: 'string',
      demand: true,
    })
    .alias('h', 'help')
    .help('h', 'Show help.')
    .argv;

  OPTIONS.directory = fs.realpathSync(argv.directory);

  startApp(); // etc .....

}

exports.getOptions = getOptions;

Example call:

node . --script find -d path/to/a/directory/

In fact, might be nice to convert index.js into this kind of setup (minus the script/yargs bits) so it's easy to convert to users if they need a little more flex.

mhulse commented 5 years ago

Would be interesting to transparently allow for the first arg to optionally be a script name:

$ node . find -d path/to/a/directory/