2

I need to run some code before each command runs, using the name of the command. i was unable to find anything in the yargs api docs.

specifically, i want to delete the cache created by each of my commands. for example the command foo, creates a cache in ./.tmp/foo. i want to delete only that cache before each time it runs. i can delete it from each command callback, but curious if there is a more programmatic way to do it.

does yargs have any features i can use to accomplish this?

brewster
  • 4,342
  • 6
  • 45
  • 67

1 Answers1

0

You may use Middleware, which provides transformation of parsed arguments before commands get executed.

                        --------------         --------------        ---------
stdin ----> argv ----> | Middleware 1 | ----> | Middleware 2 | ---> | Command |
                        --------------         --------------        ---------

However, same you could use to clean the cache.

Sample Middleware

const { promisify } = require('util') // since node 8.0.0
const readFile = promisify(require('fs').readFile)

const normalizeCredentials = (argv) => {
  if (!argv.username || !argv.password) {
    return readFile('~/.credentials').then(data => JSON.parse(data))
  }
  return {}
}

// Add normalizeCredentials to yargs
yargs.middleware(normalizeCredentials)

// yargs parsing configuration
var argv = require('yargs')
  .usage('Usage: $0 <command> [options]')
  .command('login', 'Authenticate user', (yargs) =>{
        return yargs.option('username')
                    .option('password')
      } ,(argv) => {
        authenticateUser(argv.username, argv.password)
      },
      [normalizeCredentials]
     )
  .argv;
Sourabh
  • 1,515
  • 1
  • 14
  • 21