This is the fifth day of my participation in Gwen Challenge

preface

Today, we start to update cli-related modules. We will explain these modules one by one in the early stage and integrate all modules to support the development of CLI tools at the end. Today, we will start with the most commonly used module Commander

What is the Commander module

The Commander module is a third party module, which means you need to download it from the NPM package. It gives you scaffolding commands out of the box, which greatly simplifies development. Let’s take a look at the simplest example:

const program = require('commander');
program.version('0.0.1'.'-v, --version').parse(process.argv);
// shell
node ./20210612/1.js -v
output: 0.01.
Copy the code

As mentioned above: The version method provides a way to view the current scaffold version. There are several common methods:

The option method

Use the option method to define options for the COMMANDER option. The parameters are parsed as follows:

  1. A custom flag refers to the name of a parameter passed in after a specific parameter. It can be separated by commas, vertical lines, or Spaces. It can be followed by optional parameters and mandatory parameters
  2. Option description, omitted without error, used when –help is displayed
const {program} = require('commander')
program
.option('-p, --process <type>'.'this is process')
program.parse(process.argv);
const options = program.opts();
console.log(options); //{ process: '1' }
Copy the code

command

This command is used to add a command name. The command name, description, and configuration options are described as follows

const {program} = require('commander')
program
  .command('clone <source> [destination]')
  .description('clone a repository into a newly created directory')
Copy the code

action

The command function is usually implemented with the action function. The action function takes a function whose parameters are the parameters defined in the command. We can use this matching method to do a lot of things.

const {program} = require('commander')
program
  .command('clone <source> [destination]')
  .description('clone a repository into a newly created directory')
  .action(require('./clone.js'));
program.parse(process.argv);
// clone.js
module.exports = (target, desc) = > {
    console.log(target, desc)
    const {spawn} = require('child_process');
    target = require('path').resolve(__dirname, target)
    desc = require('path').resolve(__dirname, desc)
    const child = spawn('cp'['-r', target, desc]);
    child.stdout.pipe(process.stdout);
    child.stderr.pipe(process.stderr);
}
Copy the code

As shown above, we performed clone operation according to action parameters, and the file was successfully copied

conclusion

That’s all for today, thank you