Nodejs Makes Command Line Tools

Keywords: npm JSON sudo github

wcj

   

github Warehouse Source Download

This is not only a tutorial, but also a tool to output my resume from the command line, O() O() O() O() O), which is very interesting.

# Global Installation, Installation Errors Need to be preceded by sudo
$ sudo npm install -g wcj 

# Output help
$ wcj -h
  Usage: wcj Here is my personal play command![options] <package>


  Commands:

    resume|rs [options] [cmd]    Here are the details of my resume!

  Options:

    -h, --help     output usage information
    -V, --version  output the version number

# Output subcommand help
$ wcj rs -h

  Usage: resume|rs [options] [cmd]

    //Here are the details of my resume!

  Options:

    -h, --help              output usage information
    -b, --basicinfo [type]  Essential information
    -e, --education [type]  Education experience

  basicinfo Explain:

    preview Preview resume

    -b, --basicinfo Essential information
       name : Name
       height : height
       dateOfBirth : Date of birth
       workExperience : Hands-on background
       mobile : Phone number
       telephone : Phone number
       email : E-mail address
       residency : Place of residence
       currentSituation : Present situation
       currentCity : Current city
       nation : Country
       region : region
       postalCode : Zip address
       ID : ID ID
       website : Personal net profit
       maritalStatus : Marital status
       politicalStatus : Political outlook
    -e, --education Education experience

In the process of using Nodejs, many packages support global installation, provide a command, and then we can complete some tasks on the command line. Sometimes we need to develop such command tools. In Node.js, I found it particularly easy to get a command-line tool. I'll learn how to use Node.js to generate my own command commands, which will be convenient for me in future projects.

  • Let's take a small example and feel the charm of the command line.

  • Then use the command line to export your resume (which I think might be interesting)

  • Common commands are added

    • ls View Current Directory

    • Ls-a includes hidden files

    • Open the current directory

  • Let's plan that first.

Small example

One thing you need to confirm before you start writing is that you have installed it. Node.js . You can run it from the command line. Node to confirm whether it has been installed or run node-v to see the version of node. If you've installed node, you can see output similar to the following, usually with node.js installed Incidental npm tools are installed automatically.

$ which node
/usr/local/bin/node  

$ node -v
v0.10.36

Create directory

First, create a folder at will, initialize the package.json file, and create the bin directory under the folder:

$ mkdir wcj #Create a folder
$ cd wcj && mkdir bin
$ npm init #Initialize the `package.json'file

Write the command line

In the cd to bin directory, create a new wcj.js file (name taken), write the following code, add #!/usr/bin/env at the top of the JS file node:

#!/usr/bin/env node  
var fs = require("fs"),
    path = process.cwd();

var run= function (obj) {
    if(obj[0] === '-v'){
        console.log('version is 1.0.0');
    }else if(obj[0] === '-h'){
        console.log('Useage:');
        console.log('  -v --version [show version]');
    }else{
        fs.readdir(path, function(err, files){
            if(err){
                return console.log(err);
            }
            for(var i = 0; i < files.length; i += 1){
                console.log(files[i]);
            }
        });
    }
};
//Get the parameters after the first command is removed, using space splitting
run(process.argv.slice(2)); 

The #!/ usr/bin/env node above is called shebang, indicating that the current folder is executed with the program shown in the following path. You also need a package.json file

{
  "name": "wcj",
  "version": "1.0.0",
  "description": "wcj ---",
  "repository": {
    "type": "git",
    "url": "https://github.com/jaywcjlove/wcj.git"
  },
  "main": "index.js",
  "bin": { "wcj": "bin/wcj.js" },
  "author": "kenny wang <wowohoo@qq.com> ",
  "license": "MIT"
}

Running node bin/wcj.js displays all the files and folder names under the current folder. This thing is really running. For more information on npm link, please See

The contents of bin in package.json file indicate that this field maps the WCJ command to your bin/wcj.js script. bin reference

This tool uses npm version number. semver Rules

"bin": { "wcj""bin/wcj.js" }

Source code

Global Running Command Debugging

Make sure you add bin nodes to the package.json file. Then open the command and enter the tool into the wcj directory

install

If there is no problem running under the project directory, you can install the current directory module globally or use this method to update your command line tools.

sudo npm install . -g

link

Or directory input npm link automatically adds global symbolic link, then you can use your own commands.

$ wcj
#README.md
#bin
#package.json

$ cmd -v
# version is 1.0.0

$ cmd -h 
#Useage:
#  -v --version [show version]

error handling

At run sudo NPM install. -g, there will be a bunch of warnings to ignore

If you have done npm link once and you link again, the following error will be reported. Even if you are npm Unink will also report the following error:

npm link
npm ERR! Darwin 14.3.0
npm ERR! argv "node" "/usr/local/bin/npm" "link"
npm ERR! node v0.10.36
npm ERR! npm  v2.7.1
npm ERR! path /usr/local/bin/wcj
npm ERR! code EEXIST

npm ERR! Refusing to delete: /usr/local/bin/wcj not in /Applications/XAMPP/xamppfiles/htdocs/git/github.com/myJS/wcj
File exists: /usr/local/bin/wcj
Move it away, and try again.

Let you delete / usr/local/bin/wcj and npm Remove this directory and run rm-rf/usr/local/bin/wcj

Release installation

Publish to npm

Publication must be registered. npm Account number, as well as ____________ github Account number, how to play it? Aunt Google. stay JSLite.io There are also tutorials.

npm publish

install

If you publish it npm In this way, you can run the following command.

sudo npm install -g wcj

Example download: v1.0.1

Commander

Depending on nodejs native development command tools is cumbersome. Commander.js Help us simplify command line development. Commander It is a lightweight, expressive and powerful command line framework. It provides powerful functions of user command line input and parameter parsing. Commander comes from a Ruby project of the same name. Commander.js Yes. TJ Write a package to help quickly develop Nodejs command line tools. TJ This product is a well-known high-productivity author in the Nodejs community. Conveniently define options (including the description of options and its callback function) and subcommands.

Characteristic

Commander's convenience lies in:

Self-recording code, auto-generating help, merging short parameters ("ABC"="-A-B-C"), default options, mandatory options, command parsing, prompts

API

Option(): Initialize custom parameter objects, set keywords and descriptions
Command(): Initialize the command line parameter object and get the command line input directly.
Command#command(): Define a command name
Command action (): Register a callback function
Command option (): To define parameters, you need to set up "keywords" and "descriptions". The keywords include "abbreviation" and "full writing". They are separated by ",","|" and "blank".  
Command parse (): parse the command line parameter argv
Command description (): Set the description value
Command usage (): Set the usage value

Reference resources: Examples of official documents

install

Install commander

sudo npm install commander

Option

Built-in option, Commander provides the program with a default - h option.

program
  .version('0.0.1')
  .option('-r, --resume', 'resume');
program.parse(process.argv);

The parse function handles the defined option s and sub-command s, parses the command line parameters and triggers the corresponding callbacks (as described below).

./bin/wcj.js -h
## Output the following
  Usage: wcj [options]

  Options:

    -h, --help     output usage information
    -V, --version  output the version number
    -r, --resume   resume

You can see that there is a - h parameter by default, which will output the help information of the wcj command when it is passed in.

Custom option

Add an option to the wcj command, and the presentation is my resume.

program
  .version('0.0.1')
  .option('-r| --resume', 'resume');
program.parse(process.argv);

if (program.resume) {
    console.log('resume - '
        + 'This is my resume!'
    );
}

option() receive Four parameters

  • In the first parameter, -r is short option,--resume is the corresponding long option, the separator for both is | or,. When used on the command line, these two are equivalent. The difference is that the latter can get the value of the option in the program by program.resume, where the value of the option is bool or a string.

  • The second is the option description, which will be displayed in the help information.

  • The third parameter is the callback function

  • The fourth parameter is the default value

Unknown option

When an undefined option is received, the program automatically throws an error

./bin/wcj.js -h

## Output the following
error: unknown option '--res'

Commander also provides an api to cancel this automatic error reporting mechanism,.allowUnknownOption().

#!/usr/bin/env node
program
    .allowUnknownOption()
    .version('0.0.1')
    .option('-r, --resume', 'resume');

program.parse(process.argv);
//Eliminate some details.

Option types

Command supports the following two types of options: required, optional, and bool

required and optional

In the first parameter of option, except short, long Option, you can also specify the option type, and the delimiter is also | and, where

  • The <lang> required parameter must follow the parameter value when used. Otherwise, the program will report errors.

  • [db] optional parameter, followed by the choice of whether to follow the parameter value

#!/usr/bin/env node  
var program = require('commander');
program
    .allowUnknownOption()
    .version('0.0.1')
    .option('-r, --resume', 'resume')
    .option('-l, --language <lang>', 'This language is what I am good at.')
    .parse(process.argv);

if (program.resume) {
    console.log('resume'
        + '-'
        + 'This is my resume!'
    );
}

if (program.language) console.log('language: Language I'm good at`' + program.language + '`');
if (program.database) console.log('db: Language I'm good at`' + program.database + '`');

Look at the effect

./bin/wcj.js -l python
## output
language: Language I'm good at`python`
db: Language I'm good at`MySQL`

./bin/wcj.js -l
## output
  error: option '-l, --language <lang>' argument missing

bool

The option value is Boolean, like the -- date above, which defaults to false. When this parameter is used, the program.date is true. Otherwise false

There is a variant of bool option when long When option is defined as no - * the default value is true. take

var program = require('commander');
program
  .option('-d, --no-date', 'don't display current date')
  .parse(process.argv);

var dt = new Date();
if (program.date) {
    console.log(dt.getFullYear()
        + '-'
        + (dt.getMonth() + 1)
        + '-'
        + dt.getDate()
    );
}

Without the - d parameter, the default value of the parameter is true

Automated --help

Commander automatically generates help information based on configuration option s, sub-command s and other information.

Custom help

Additional help information can be output by listening for -- help events, as shown below with some examples added to the fe command

// must be before .parse() since node's emit() is immediate
program.on('--help', function () {
    console.log('  Custom examples:')
    console.log('')
    console.log('    Output command  wcj -d')
    console.log('    Output command  wcj -l python')
    console.log('')
})

program.parse(process.argv);

The results are as follows:

./bin/wcj.js -h

  Usage: wcj [options]

  Options:

    -h, --help             output usage information
    -d, --no-date          display current time
    - Language < Lang > is the language I am good at.
    - b,--database [db] This database is my best database

  Custom examples:

    Output command wcj-d
    Output command wcj-l Python

Commands like git style

Source code

#!/usr/bin/env node 
var program = require('commander');
var appInfo = require('./../package.json');

program
    .version(appInfo.version)
    .usage('Here is my personal play command![options] <package>')

//Subcommands like git style
program
    //Sub command
    .command('resume <cmd>')
    //Short Command-Short Writing
    .alias('rs')
    //Explain
    .description('Here are the details of my resume!')
    //Subcommands of resume
    .option("-n, --name <mode>", "Output my name")
    //Register a callback function
    .action(function(cmd, options){
        var nm = typeof options.name=='string'?options.name:""

        console.log('resume "%s" Use %s Pattern', cmd, nm);
    }).on('--help', function() {
        //Here output the help of subcommands
        console.log('  Examples:');
        console.log('    Operating method:');
        console.log('    $ ./bin/wcj.js resume ss -n aaaaa');
        console.log('    $ ./bin/wcj.js resume ss');
        console.log();
    });

program.parse(process.argv);

Running output mode of the above example

$ ./bin/wcj.js resume ss -n aaaaa

Output:
resume "ss" uses aaaaa mode

$ ./bin/wcj.js resume ss
 Output:
resume "aa" usage pattern

event listeners

As many commands as you name, you listen to as many commands as you want -- help is the default listener event.

program.on('--help', function(argv,test){
    process.exit(1);
});

yargs

Command line framework yargs interacts with your program yargs for github

var argv = require('yargs').argv;
if (argv.l == 'zh-cn') {
    console.log('Chinese site!');
}else if(argv.l == 'en') {
    console.log('English website!');
}

Use

var argv = require('yargs').argv;
if (argv.l == 'zh-cn') {
    console.log('Chinese site!');
}else if(argv.l == 'en') {
    console.log('English website!');
}

Reading reference

The first small example read a lot of articles, record, feel very simple.

Posted by manoj_jnics1 on Tue, 09 Apr 2019 11:57:32 -0700