— — — — — fostered fostered fostered — — — — —

Node series address:

  • Code repository: github.com/LiangJunron…
  • Article repository: github.com/LiangJunron…

— — — — — fostered fostered fostered — — — — —

Commander.js – The complete Node.js command-line solution.

This article explains how to stroll the Node.js command line using commander.js.

A directory

What’s the difference between a free front end and a salted fish

directory
A directory
The preface
Three commander. Js
Practice: file rearrangement function
 4.1 Practice Catalog
 4.2 write a commander
 4.3 Write the sorting function
 4.4 Running Content
Five Common Commander Configurations
Vi References

The preface

Returns the directory

When a Node.js program is running, there are many global variables that are stored in memory.

Where process is the process object, it has an argv attribute and can view instructions.

To create a random index.js example, run the node index.js –name jsliang command

index.js

console.log(process.argv);
/* [ 'C:\\Program Files\\nodejs\\node.exe', 'F:\\jsliang\\index.js', '--name', 'jsliang' ] */
Copy the code

Look at the printed data:

  • NodeLocation:C:\\Program Files\\nodejs\\node.exe
  • Current code path:F:\\jsliang\\index.js
  • Parameter 1:--name
  • Argument 2:jsliang

So, when we write a command line program, we only need to parse the third element of process.argv and its subsequent arguments.

If it’s not too much trouble, you can write a lot of branches to do it.

However, why do you need to write your own, if you can be lazy ~

Three commander. Js

Returns the directory

Commander. Js is a toolkit written by TJ to make Node command line programming easier:

  • Making: commander

README: github.com/tj/commande…

Let’s start:

  • Initialize thepackage.json:npm init --yes
    • !!!!! [Note] This step can be omitted if the Node series is learned in sequence
    • !!!!! [Note] The following code can create atestEmpty folders to fool around with
  • The installation package:npm i commander
  • Write instruction file:

index.js

const program = require('commander');

program
  .version('0.0.1')
  .description('Gadget Instruction List')
  .option('-s, --sort <path>'.'Sorting function'.' ')

program.parse(process.argv);
Copy the code

Package. json (automatically generated)

{
  "name": "test"."version": "1.0.0"."description": ""."main": "index.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": []."author": ""."license": "ISC"."dependencies": {
    "commander": "^ 7.2.0"}}Copy the code

The logic of this code is as follows:

  1. referencecommander
  2. describecommanderversionParameters such as
  3. withcommandercontrolprocess.argv

Focus on the argument in paragraph 2 of this code:

Parameters look very annoying, but do not know and do not know how to use

  • versionVersion:
    • Usage:.version('x.y.z')
  • descriptionDescription:
    • Usage:.description(' Gadget instruction list ')
  • optionOptions:
    • Usage:.option('-n, --name <name>', 'your name', 'jsliang')
    • The first parameter is the option definition, which you can use|..' 'Space connection
    • The second parameter is the option description
    • The third parameter is optional parameter Default value (optional)

So we can look at some information below.

  • Execute command:node index.js -h

The following results are obtained:

Usage: index [options] Gadget instruction list Options: -v, --version output the version number -s, --sort <path> sort function (default: "") -h, --help display help for commandCopy the code

So we’ve done some little instructions, so how do we do that?

  • Sorting:node index.js -s "jsliang"

NPM run dev, NPM run XXX.

Of course it can!

Practice: file rearrangement function

Returns the directory

So much said, do a little practice!


For Markdown’s document library, if you don’t set the document order, it will read the directory according to the system’s rules:

  • 1. The article 1
  • Article 10. 10
  • Article 2. 2

When the contents of a folder are too much, we want to let users read in their own order, so we can not find the system, so we need to use Node to write a small tool, when reading according to the desired order to read, this is our original intention to develop small tools.

Of course, there is also an important feature when we want to insert an article between articles 1 and 2, for example:

  • 1. The article 1
  • 1-1. Article 1-1
  • Article 2. 2

We also need to reorder the directory structure to insert new articles into the specified location.

4.1 Practice Catalog

Returns the directory

At this point our directory is:

+ docs + 3. directory c-1. Directory C1.md-1-1. Directory C2. mD-2. Directory c3. mD-1. Article a.mD-2. Article d.d + src-config.ts-index.ts [existing] -sortCatalog.ts -.eslintrc.js [existing] -package.json [existing] - Tsconfig. jsonCopy the code

The.eslintrc.js, package-lock.json, package.json, and tsconfig.json directories are created automatically.

Create a few empty Markdown files in the docs directory.

In order to avoid small partners misoperation, or cut a picture

4.2 write a commander

Returns the directory

To add commonder, simply configure package.json and index.ts.

  • Initialize thepackage.json:npm init --yes(Previously configured)
  • The installationcommander:npm i commander

package.json

{
  "name": "jsliang"."version": "1.0.0"."description": "FE-util"."main": "index.js"."scripts": {
    "sort": "ts-node ./src/index.ts sort"
  },
  "keywords": []."author": ""."license": "ISC"."devDependencies": {
    "@types/node": "^ 15.0.2"."@typescript-eslint/eslint-plugin": "^ 4.23.0"."@typescript-eslint/parser": "^ 4.23.0"."eslint": "^ 7.26.0"."ts-node": "^ 9.1.1." "."typescript": "^ 4.2.4"
  },
  "dependencies": {
    "commander": "^ 7.2.0"}}Copy the code

Notice that scripts have changed, so copy that back

Then simply write the contents of index.ts

src/index.ts

import program from 'commander';
import { sortCatalog } from './sortCatalog';

program
  .version('0.0.1')
  .description('Library of Tools')

program
  .command('sort <path>')
  .description('File sorting function. Example: NPM run sort "docs" or NPM run sort "C:/code/jsliang/ SRC /docs"')
  .action((path: string) = > {
    sortCatalog(`.. /${path}`); // For convenience, go back one layer to the outside
  });

program.parse(process.argv);
Copy the code

4.3 Write the sorting function

Returns the directory

Once you have the basic configuration ready, just add something to sortCatalog.ts:

src/sortCatalog.ts

/ * * *@name File sorting function *@time The 2021-05-22 16:08:06 *@description Rule 1. System order 1/10/2/21/3, want to order 1/2/3/10/21 2. Insert file 1/2/1-1, want to sort by 1/2/2/3 */
import fs from 'fs';
import path from 'path';
import { IGNORE_PATH } from './config';

const recursion = (filePath: string, level = 0) = > {
  const files = fs.readdirSync(filePath);

  files
    .filter((item= >! IGNORE_PATH.includes(item)))// Filter ignores files/folders
    .sort((a, b) = >
      Number((a.split('. ') [0]).replace(The '-'.'. '))
      - Number((b.split('. ') [0]).replace(The '-'.'. ')))// Sort folders
    .forEach((item, index) = > { // Walk through the folder
      // Set the old file name and new file name
      const oldFileName = item;
      const newFileName = `${index + 1}.${oldFileName.slice(oldFileName.indexOf('. ') + 1)}`;

      // Set the old file path and new file path
      const oldPath = `${filePath}/${oldFileName}`;
      const newPath = `${filePath}/${newFileName}`;

      // Determine the file format
      const stat = fs.statSync(oldPath);

      // Determine whether it is a folder or a file
      if (stat.isFile()) {
        fs.renameSync(oldPath, newPath); // Rename the file
      } else if (stat.isDirectory()) {
        fs.renameSync(oldPath, newPath); // Rename the folder
        recursion(newPath, level + 1); // Recursive folder}}); };export const sortCatalog = (filePath: string): boolean= > {
  // Absolute path
  if (path.isAbsolute(filePath)) {
    recursion(filePath);
  } else { // Relative path
    recursion(path.join(__dirname, filePath));
  }

  return true;
};
Copy the code

Config. ts is a global configuration.

/ * * *@name Default global configuration *@time The 2021-05-22 16:12:21 * /
import path from 'path';

// Base directory
export const BASE_PATH = path.join(__dirname, './docs');

// Ignore the directory
export const IGNORE_PATH = [
  '.vscode'.'node_modules',];Copy the code

When we don’t have one, we give the default one.

4.4 Running Content

Returns the directory

OK, when we’re ready, we’re ready to play.

The current directory structure under Docs is:

- 1. Article A.md-10. Article D.Md-2. Directory C-1-1. Directory C2.md-1. Directory C1.md-2. Directory c3. The mdCopy the code

After we run NPM run sort “docs”, the new directory list becomes:

- 1. Article A.md-2. Article B.Md-3. Directory C1.md-2. directory c2.md-3. directory c3.mD-4. The article d.m dCopy the code

In this way, our simple case is ready! Isn’t it very simple?

Five Common Commander Configurations

Returns the directory

Here are some examples of commander configurations that we really don’t want to see, but are common enough to use:

  • version: version. Used to set the version number of a command program
    • Usage:.version('x.y.z')
  • description: describe. Used to set the command description
    • Usage:.description(' Gadget instruction list ')
  • option: options.
    • Usage:.option('-n, --name <name>', 'your name', 'jsliang')
    • The first parameter is the option definition, which you can use|..' 'Space connection, parameters can be used<>(Required) or[](Optional) Modify
    • The second parameter is the option description
    • The third parameter is optional parameter Default value (optional)
  • commandCommand:
    • Usage:.command('init <path>', 'description')
    • commandThe usage is slightly complicated. In principle, it takes three parameters: the first is the command definition, the second is the command description, and the third is the command auxiliary modifier object
    • The first parameter can be used<>or[]Modify command parameters
    • The second parameter is optional
      • When there is no second argument,commander.jsWill returnCommandobject
      • When the second argument is taken, the prototype object is returned and the call is not displayedaction(fn), subcommand mode will be used
      • Subcommand mode:./pm,./pm-install,./pm-searchThese subcommands are in a different file from the main command
    • The third parameter is different in that it sets whether to display the subcommand mode used
  • action: action. Used to set the related callbacks to be executed by the command
    • Usage:.action(fn)
    • fnThe acceptable arguments to the command are function parameters, in the order andcommand()The order defined in
  • parse: parsingprocess.argv
    • Usage:program.parse(process.argv)
    • This API is usually called at the end for parsingprocess.argv

OK, that’s the end of the brief introduction to Commander, and we’ll see you next time!

Vi References

Returns the directory

  • Making: commander
  • W3CSchool: Use commander. Js to create a Nodejs command-line program

Jsliang’s document library is licensed by Junrong Liang under the Creative Commons Attribution – Non-commercial – Share alike 4.0 International License. Based on the github.com/LiangJunron… On the creation of works. Outside of this license agreement authorized access can be from creativecommons.org/licenses/by… Obtained.