There may be a certain threshold when developing the command line natively using Node.js, but relying on open source modules can help simplify command-line development and get more out of the way. This article mainly uses some examples to demonstrate the basic gameplay of Commander. Js and Inquirer. Below the old driver will take me, I take everyone to play Node command line!

Warm prompt

  • Part of the code in this paper refers to Athena, a front-end process tool from Bump Laboratory
  • This article requires a little Node basics
  • This article covers some ES6 syntax, and make sure Node is 4.0 or later
  • The knowledge point that does not belong to this article takes a second to pass ha

Basis of preparation

1. Create a project, run CMD init, and create package.json

2. Create a system file without the suffix in the root directory as the main entry file

3. Install modules commander, Inquirer, chalk, If you run NPM install commander Inquirer chalk — save-dev in the root directory, you will see a node_modules directory in the root directory, which contains the modules you just installed. In package.json, devDependencies relies on these modules, as shown belowThe root directory

package.json

"Name" : "app", "version" : "1.0.0", "description" : "to play the command-line development", "main" : "index. Js", "scripts" : {" test ", "echo \" Error: No test specified\" && exit 1" "author": "ykg", "license": "ISC", "devDependencies": {"chalk": "^1.1.3", "commander": "^ 2.9.0 inquirer", ""," ^ 1.1.2. ""Copy the code

The main content

Let’s get to know Commander

Commander profile

Commander, inspired by Ruby, provides powerful user command line input and parameter parsing to help simplify command-line development. According to its official description, it has the following features:

  • Argument parsing
  • Mandatory polymorphism
  • Variable parameter
  • Git style subcommands
  • Automated help information
  • Customize help

A simple example

Let’s take a look at the basic syntax with a simple example

const program = require('commander') const inquirer = require('inquirer') const chalk = require('chalk') program .command('module').alias('m').description(' create new module').option('-a, --name [moduleName]', Parse (process.argv).action(option => {console.log('Hello World') program.parse(process.argv)Copy the code

Execute it and see the effect! $node.js app ($node.js app) // Output Hello World

Run in global mode

We can do this in three steps through some configuration and then run it as module name + command:

  • Configure the bin field of package.json. What is the bin field useful for? It can be used to store an executable file, as shown in the following configuration

  • Execute NPM link. It will copy the app field into NPM’s global module installation folder node_modules and create a symbolic link (soft link) that adds the PATH of app to the environment variable PATH

  • Add code at the top of the main entry file#! /usr/bin/env node, indicating that this is an executable application, as shown below
    const program = require('commander') const inquirer = require('inquirer') const chalk = require('chalk') program .command('module').alias('m').description(' create new module').option('-a, --name [moduleName]', Parse (process.argv).action(option => {console.log('Hello World') program.parse(process.argv)Copy the code

Once you’ve done all three steps, run $app Module // and print Hello World

commander API

Let’s take a look at the function of each attribute one by one to understand it in a second

  • Command – Defines a command line directive, followed by a name separated by a space, e.g..command(‘ app [name] ‘)
  • Alias – Defining a shorter command line directive, such as executing the command $app m, is equivalent
  • Description – Description, which will be shown in help
  • Option – Defines parameters. It accepts four parameters, in the first parameter, and it can enter a short name – a long name – app, use | or separated, when used in the command line, the two are equivalent, the difference is that the latter can be in the program through the callback is available; The second is the description, which will be displayed in the help message; The third parameter is the callback function, which takes a string as an argument. Sometimes we need a command line to create multiple modules, so we need a callback. The fourth parameter is the default value
  • Action – Registers a callback function. Note that the callback does not currently support let declarations
  • Parse – Parses the command line

Generate Help information

Automatically generate

Run $app m -help

It automatically displays description and option information in help

Custom generation

Help can also be generated in a custom way

const program = require('commander') const inquirer = require('inquirer') const chalk = require('chalk') program .command('module [moduleName]').alias('m').description(' create new project ').option('-a, --name [moduleName]', Action (option => {console.log('Hello World').on('--help', function() { console.log(' Examples:') console.log('') console.log('$ app module moduleName') console.log('$ app m moduleName') program.parse(process.argv)Copy the code

Run $app m -help

inquirer

In the development process, we need to frequently interact with the command line, with the help of the Inquirer module can easily achieve this, it provides the user interface and query session flow. Its syntax looks like this (copied directly from official ~~)

var inquirer = require('inquirer')
inquirer.prompt([]).then(function (answers) {Copy the code

Note that in the old syntax, the traditional function callback was used

var inquirer = require('inquirer')
inquirer.prompt([], function (answers) {Copy the code
Inquirer features introduction
  • Input – the input
  • Validate – validation
  • List – List options
  • Confirm – tip
  • Checkbox – checkboxes and so on

This module is quite simple, a look will make it all clear

const program = require('commander') const inquirer = require('inquirer') const _ = require('lodash') const chalk = Require ('chalk') program.command ('module').alias('m').description(' create new module').option('--name [moduleName]') .option('--sass', 'enable sass').option('--less',' enable less').action(option => {var config = _. Assign ({moduleName: null, description: '', sass: false, less: false }, option) var promps = [] if(config.moduleName ! == 'string') {promps.push({type: 'input', name: 'moduleName', message: 'please input the moduleName', validate: function (input){if(! Input) {return 'cannot be null' return true if(config.description! == 'string') { promps.push({ type: 'input', name: 'moduleDescription', message: 'Please enter module description' if(config.sass === false && config.less === false) {promps.push({type: 'list', name: 'cssPretreatment', message: 'What CSS preprocessor do you want to use ', choices: [name: 'Sass/Compass', value: 'Sass' name: 'Less', value: 'less' inquirer.prompt(promps).then(function (answers) { console.log(answers) .on('--help', function() { console.log(' Examples:') console.log('') console.log('$ app module moduleName') console.log('$ app m moduleName') program.parse(process.argv)Copy the code

Run $app m

The promps array is used to accept parameters and the LoDash module’s Assign method is used to merge objects. Lodash is not part of this chapter. Here we provide a Chinese API document for your reference

chalk

Finally, we introduce Chalk to beautify the command line, which is lightweight, high performance and low learning cost. Continue to introduce Chalk in the chestnut above for output

const program = require('commander') const inquirer = require('inquirer') const _ = require('lodash') const chalk = Require ('chalk') program.command ('module').alias('m').description(' create new module').option('--name [moduleName]') .option('--sass', 'enable sass').option('--less',' enable less').action(option => {var config = _. Assign ({moduleName: null, description: '', sass: false, less: false }, Option) var promps = [] console.log('') console.log('') console.log('') console.log('') if(config. ModuleName! == 'string') {promps.push({type: 'input', name: 'moduleName', message: 'please input the moduleName', validate: function (input){if(! Input) {return 'cannot be null' return true if(config.description! == 'string') { promps.push({ type: 'input', name: 'moduleDescription', message: 'Please enter module description' if(config.sass ===false && config.less ===false) {promps.push({type: 'list', name: 'cssPretreatment', message: 'What CSS preprocessor do you want to use ', choices: [name: 'Sass/Compass', value: 'Sass' name: 'Less', value: 'less' inquirer. Prompt (promps). Then (function (answers) {console.log(chalk. Green (' chalk ')) console.log(chalk. Blue (' chalk ')) Console. log(chalk. Blue. BgRed (' finished ')) console.log(chalk. Blue (answers)). On ('--help', function() { console.log(' Examples:') console.log('') console.log('$ app module moduleName') console.log('$ app m moduleName') program.parse(process.argv)Copy the code

Run $app m

As you can see from the output, this article is finished.

For a long time, I didn’t know what the old driver was. As time went on and I understood the context of the word in real life, my subconscious thought of it as one

The vocabulary of… Later only to know that the real old driver refers to in each website, forum contact time is relatively long, familiar with the station of various rules, content and technology, gameplay, and master a certain resource of the veteran, also refers to in some aspects of the door familiar with the road, seniority is older, a wide range of knowledge, experience enough people…

reference

Bump laboratory front-end process tools: github.com/o2team/athe… Blog: www.tuicool.com/articles/ZF… Commander: www.npmjs.com/package/com… The inquirer: www.npmjs.com/package/inq… Chalk: www.npmjs.com/package/cha… Example source: github.com/yangzicheng… Last update: 2016-08-10 17:06:11