I am currently studying the MOOCs front-end architect course, but I am still not familiar with many things. So ready to learn each content output below, today is the first day.


There are two packages in the folder, simoon-test and simoon-test-lib, as shown in Figure 1-1. In simoon-test, run the command to parse the parameters. For example, node simoon-test init –name test and node simoon-test –version.

The simoon-test-lib file is used to accept the recipients of the parsed parameters in the simoon-test file. The main code is as follows:

module.exports = {
    sum(a, b) {
        return a + b
    init({ option, param }) {
        console.log('Execute init method', option, param)
Copy the code

Command registration and parameter resolution

Step 1: Under simoon-test, run NPM link simoon-test-lib

Step 2: Introduce simoon-test-lib

In Node, require(‘process’).argv, to get arguments in the command.

let argvs = require('process').argv;
Copy the code

Execute node bin/index.js init to get argvs as follows:

'/ Users/MAC /. NVM/versions/node/v10.15.3 / bin/node'./Volumes/ Learn/Simoon-test /bin/index.js'.'init'.'--name'.'test' 
Copy the code

In this case, the third parameter you see is init, followed by parameters. So I need to intercept argvs to get options.

let command = argvs[2];
const options = argvs.splice(3);
Copy the code

To make a judgment here, if the length of options is greater than 1, execute the method in simoon-test-lib. Some simple things need to be done internally:

  • Get option and param from options
  • Remove — from option (e.g. –name becomes name)
  • Based on the parameters, execute the methods in simoon-test-lib
if (options.length > 1) {
    let [option, param] = options;
    option = option.replace(The '-'.' ');
    if (command) {
        if (lib[command]) {
            lib[command]({ option, param })
        } else {
            console.log('Invalid command')}}else {
        console.log('Please enter command')}}Copy the code

Global command parsing

There are cases, such as vue –version, in which the third argument is the one that starts with –. This is called a globalOption.

In this case, a separate treatment is required. The treatment methods are as follows:

let command = argvs[2];
if (command.startsWith(The '-') || command.startsWith(The '-')) {
    const globalOption = command.replace(/--|-/g.' ')
    if (globalOption === 'version' || globalOption === 'V') {
        console.log('Current version is: v1.0.0')}}Copy the code

If the third argument to argv starts with — or -, it will be replaced with — or -. And then we do some processing.

The last

Today so much, arch a pawn, continuous refinement (volume).

Source: github.com/haimingyue/…