Node.js Development Command Line Program tutorial detailed

Source: Internet
Author: User
Tags commit stdin

One, executable script

Let's start with the simplest of words.

First, using the JavaScript language, write an executable script hello.


#!/usr/bin/env node
Console.log (' Hello World ');

Then, modify the permission for Hello.


$ chmod 755 Hello

Now, hello is ready to execute.


$./hello
Hello World

If you want to remove the path in front of Hello, you can add the path of hello to the environment variable path. Another better approach, however, is to create a new Package.json in the current directory and write to the following content.


{
"Name": "Hello",
"Bin": {
"Hello": "Hello"
}
}

Then execute the NPM link command.


$ NPM Link

Now that you're done with Hello, you don't have to enter the path.


$ hello
Hello World

the original wording of command line parameters

Command line arguments can be obtained using the system variable PROCESS.ARGV.


#!/usr/bin/env node
Console.log (' Hello ', process.argv[2]);

When executed, directly behind the script file, add the parameters.


$/hello Tom
Hello, Tom.

iii. New Process

Scripts can create a new subprocess through the Child_process module to execute Unix system commands.


#!/usr/bin/env node
var name = process.argv[2];
var exec = require (' child_process '). exec;

var child = exec (' echo hello ' + name, function (err, stdout, stderr) {
if (err) throw err;
Console.log (stdout);
});

Usage is as follows.


$/hello Tom
Hello, Tom.

Four, Shelljs module

The Shelljs module repackaged the child_process, calling system commands more convenient. It needs to be installed after use.


NPM Install--save Shelljs

Then, rewrite the script.


#!/usr/bin/env node
var name = process.argv[2];
var shell = require ("Shelljs");

Shell.exec ("echo Hello" + name);

The code above is the native mode of Shelljs, which executes the shell command through the Exec method. In addition, there is a global model that allows you to write shell commands directly in your script.


Require (' Shelljs/global ');

if (!which (' git ')) {
Echo (' Sorry, this script requires git ');
Exit (1);
}

mkdir (' P ', ' out/release ');
CP (' R ', ' stuff/* ', ' out/release ');

CD (' Lib ');
LS (' *.js '). ForEach (function (file) {
Sed (' i ', ' build_version ', ' v0.1.2 ', file);
Sed (' i ',/.*remove_this_line.*\n/, ', file ');
Sed (' i ',/.*replace_line_with_macro.*\n/, Cat (' Macro.js '), file);
});
CD ('.. ');

if (exec (' git commit-am ' auto-commit '). Code!== 0) {
Echo (' Error:git commit failed ');
Exit (1);
}

Five, Yargs module

Shelljs only solves how to invoke the shell command, and the Yargs module can resolve how to handle command-line arguments. It also needs to be installed.


$ NPM Install--save Yargs

The Yargs module provides a argv object for reading command-line arguments. Please look at the rewritten hello.


#!/usr/bin/env node
var argv = require (' Yargs '). argv;

Console.log (' Hello ', argv.name);

When used, the following two usages are available.


$ Hello--name=tom
Hello, Tom.

$ Hello--name Tom
Hello, Tom.

If you change the argv.name to ARGV.N, you can use a short parameter form of a letter.


$ hello-n Tom
Hello, Tom.

You can use the alias method to specify that name is an alias for N.


#!/usr/bin/env node
var argv = require (' Yargs ')
. Alias (' n ', ' name ')
. argv;

Console.log (' Hello ', ARGV.N);

As a result, both short and long parameters can be used.


$ hello-n Tom
Hello, Tom.
$ Hello--name Tom
Hello, Tom.

The ARGV object has an underscore (_) property that allows you to get a parameter that begins with a non-conjunctions line.


#!/usr/bin/env node
var argv = require (' Yargs '). argv;

Console.log (' Hello ', ARGV.N);
Console.log (argv._);

Usage is as follows.


$ Hello a-n Tom B C
Hello, Tom.
[' A ', ' B ', ' C ']

vi. Configuration of command line parameters

The Yargs module also provides 3 methods for configuring command line parameters.

Demand: Must be selected
Default: Defaults
Describe: Tips


#!/usr/bin/env node
var argv = require (' Yargs ')
. demand ([' n '])
. Default ({n: ' Tom '})
. Describe ({n: ' Your Name '})
. argv;

Console.log (' Hello ', ARGV.N);

The above code specifies that the n parameter cannot be omitted, the default value is Tom, and a line of hints is given.

The options method allows you to write all of these configurations into an object.


#!/usr/bin/env node
var argv = require (' Yargs ')
. option (' n ', {
Alias: ' Name ',
Demand:true,
Default: ' Tom ',
Describe: ' Your name ',
Type: ' String '
})
. argv;

Console.log (' Hello ', ARGV.N);

Sometimes, some parameters do not require a value, only play a switch, then you can specify these parameters in a Boolean method to return a Boolean value.


#!/usr/bin/env node
var argv = require (' Yargs ')
. Boolean ([' N '])
. argv;

Console.log (' Hello ', ARGV.N);

In the code above, parameter n always returns a Boolean value, as follows.


$ hello
Hello False
$ hello-n
Hello True
$ hello-n Tom
Hello True

The Boolean method can also be used as a property to write to the option object.


#!/usr/bin/env node
var argv = require (' Yargs ')
. option (' n ', {
Boolean:true
})
. argv;

Console.log (' Hello ', ARGV.N);

Vii. Help Information

The Yargs module provides the following methods for generating help information.

Usage: Usage format
Example: providing examples
Help: Displaying assistance information
Epilog: Appears at the end of the Help information


#!/usr/bin/env node
var argv = require (' Yargs ')
. Option (' F ', {
Alias: ' Name ',
Demand:true,
Default: ' Tom ',
Describe: ' Your name ',
Type: ' String '
})
. Usage (' Usage:hello [options] ')
. Example (' Hello-n Tom ', ' Say hello to Tom ')
. Help (' H ')
. Alias (' H ', ' help ')
. Epilog (' Copyright 2015 ')
. argv;

Console.log (' Hello ', ARGV.N);

The results of the implementation are as follows.


$ hello-h

Usage:hello [Options]

Options:
-F,--name your name [string] [required] [default: "Tom"]
-H,--help show help [Boolean]

Examples:
Hello-n Tom say hello to Tom

Copyright 2015

viii. Sub-command

The Yargs module also allows you to set the Git-style subcommand by using the command method.


#!/usr/bin/env node
var argv = require (' Yargs ')
. Command ("Morning", "Good Morning", function (Yargs) {
Console.log ("Good Morning");
})
. Command ("Evening", "Good Evening", function (Yargs) {
Console.log ("Good Evening");
})
. argv;

Console.log (' Hello ', ARGV.N);

Usage is as follows.


$ Hello morning-n Tom
Good morning
Hello, Tom.

This function can be combined with the Shellojs module.


#!/usr/bin/env node
Require (' Shelljs/global ');
var argv = require (' Yargs ')
. Command ("Morning", "Good Morning", function (Yargs) {
Echo ("Good Morning");
})
. Command ("Evening", "Good Evening", function (Yargs) {
Echo ("Good Evening");
})
. argv;

Console.log (' Hello ', ARGV.N);

Each subcommand often has its own parameters, which need to be specified separately in the callback function. callback function, you reset the Yargs object with the Reset method first.


#!/usr/bin/env node
Require (' Shelljs/global ');
var argv = require (' Yargs ')
. Command ("Morning", "Good Morning", function (Yargs) {
Echo ("Good Morning");
var argv = Yargs.reset ()
. Option ("M", {
Alias: "Message",
Description: "Provide any sentence"
})
. Help ("H")
. Alias ("H", "help")
. argv;

Echo (ARGV.M);
})
. argv;

Usage is as follows.


$ Hello morning-m "Are you Hungry?"
Good morning
Are you hungry?

Ix. Other Matters

(1) Return value

According to Unix tradition, program execution returns 0 successfully, otherwise it returns 1.


if (err) {
Process.exit (1);
} else {
Process.exit (0);
}

(2) redirect

Unix allows you to use pipe redirection data between programs.


$ ps aux | grep ' node '

The script can get the redirected data by listening to the standard input of the date event.


Process.stdin.resume ();
Process.stdin.setEncoding (' UTF8 ');
Process.stdin.on (' Data ', function (data) {
Process.stdout.write (data);
});

Here is the usage.


$ Echo ' foo ' |./hello
Hello foo

(3) System signal

The operating system can send signals to the executing process, which can listen for signal events.


Process.on (' SIGINT ', function () {
Console.log (' Got a SIGINT ');
Process.exit (0);
});

The way to send a signal is as follows.


$ kill-s SIGINT [process_id]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.