Practical use of JavaScript to make your own command line (CLI tool) from scratch

Time:2020-6-28

Practical use of JavaScript to make your own command line (CLI tool) from scratch

We use cli programs (such as terminal, CMD, PowerShell, etc.) for software development every day. Each tool you use is essentially the product of other software engineers, and we can also make our own cli tools.

Simple cli from scratch, let’s start!

First, let’s make a simple cli tool that prints “helloword”

To make the CLI, you need to make two files

  • package.json : the specified entry will be set and configured
  • index.js : executable according to cli command

add to Package.json file

// package.json
{
  "name": "my-cli",
  "version": "0.0.1",
  "description": "nodejs cli program",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Dunizb",
  "license": "ISC"
}

stay package.json , specify metadata about the current cli program,nameversiondescriptionauthorWait.

establish index.js Executable

// index.js
#! /usr/bin/env node
console.log('Hello CLI');

So, what does the first sentence mean?

stayLinuxAnd based onUnixIn the operating system (such as MAC),#! / usr / bin / env nodeIt’s not just a comment. It is used in/usr/bin/envTo run the file.

But atWindowsThis is just a comment.

Add bin attribute

We addbinProperty to actually runindex.jsfile

// package.json
{
  "name": "my-cli",
  "version": "0.0.1",
  ...
  ...
  "license": "ISC",
  "bin": {
    "cli": "./index.js"
  }
}

binProperty has an executable,cliCommand requires runningindex.jsDocuments.

Running cli

Finally, let’s run the CLI to print on the consoleHello CLI。 By runningnpm i -gstay package.json Install the configuration in.

Practical use of JavaScript to make your own command line (CLI tool) from scratch

Next time you run on the consolenpm i -g, you getupdated 1 package..., notadded 1 package ...

Then runcliCommand. Finally,Hello CLI!

Practical use of JavaScript to make your own command line (CLI tool) from scratch

You may need to addsudoCommand (i.esudo cli), nonode_modulesFolder because you have no dependencies installed.

In cli Process.argv

// index.js
#! /usr/bin/env node
console.log('Hello CLI', process.argv);

You can useprocess.argvFind the option in the command, which is displayed as an array.

You don’t need to update every timeindex.jsRun again on codenpm i -gBecause you havepackage.jsonOfbinProperty tocliCommand andindex.jsDocuments. Therefore, every callcliAll commands can be executedindex.jsFile (it is not from the cache, so you can run new updates).

To run a command in a terminal:

cli one two three four

result

Practical use of JavaScript to make your own command line (CLI tool) from scratch

In arrayFirst two elementsyesnodeandcliThe path to the command. (for Windows systems, it may print different output) the output may vary depending on your computer settings and environment (depending on your installation on your computernodeandcliLocation of the command).

In addition,one two three fourRepresent as array type

Second, a simple cli tool for interacting with users through user input

Use is calledreadlineThe native node module of gets input from the user.

// index.js
#! /usr/bin/env node
const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.question "How are you today (happy, sad)? ", (answer) => {
  If (answer = = = "happy"){
    console.log ("I'm glad to hear that");
  }Else if (answer = = = "sad"){
    console.log ("hope you feel better tomorrow")
  } else {
    console.log ("are you happy or sad? "";
  }
    rl.close();
});

You can usereadlineIn modulecreateInterfaceMethod creationrlObject.

process.stdinandprocess.stdoutIs the console input and output stream.

readlineThe module accepts input from the user,rlThe object question method is a method of asking questions to users. The callback function has aanswerParameter (input from user), if all I / O (input and output) is complete, closerlObject.

Can we further improve the CLI by asking the user again if they don’t answer “happy” or “sad” in this case?

When you ask the user again, is the answer wrong

#! /usr/bin/env node
const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

console.clear();

const answerCallback = (answer) => {
  If (answer = = = "happy"){
    console.log ("I'm glad to hear that");
    rl.close();
  }Else if (answer = = = "sad"){
    console.log ("I hope you feel better tomorrow");
    rl.close();
  } else {
    console.log ("are you happy or sad? "";
    rl.question "How are you today (happy, sad)? ", answerCallback);
  }
};

rl.question ("how are you today?", answercallback);

When the program starts to useconsole. ClearTo clear the console, use therl.questionMethod ask the user for input and useanswerCallbackFunction to get the answer.

If the answer is neither sad nor happy, clear the console, and then recursively ask again. If the answer is sad or happy, close the input console.

last

In this article, we practiced a way to make a simple cli tool that requires user input. I hope you like reading.

More advanced and practical examples can be found on the blog.

Practical use of JavaScript to make your own command line (CLI tool) from scratch


WeChat official account for the first selection of foreign languages

Practical use of JavaScript to make your own command line (CLI tool) from scratch

Continue to read other great articles

  • 12 in 2020 Vue.js Development skills and tips
  • [tips] how can CSS achieve text alignment?
  • Seven simple but difficult JavaScript interview questions
  • Nine projects that allow you to become a front-end master in 2020
  • [actual battle] Vue.js Icon selection component development
  • The basic concept of HTTP you have to know
  • [notes] self cultivation of Web full stack engineer (I)
  • [note] self cultivation of Web full stack engineer (2)
  • [tips] how to prevent the mobile virtual keyboard from popping up on the H5 page?
  • Reject JavaScript. You must use these three CSS techniques
  • 7 Hidden chrome devtools features to improve your productivity
  • [picture and text tutorial] synchronize your vscode settings and extension plug-ins, so you don’t have to worry about switching

  • more…