Detailed description of Node. js command line program development tutorial, node. js Program Development

Source: Internet
Author: User
Tags call shell

Detailed description of Node. js command line program development tutorial, node. js Program Development

Whether a programming language is easy to use depends largely on the ability to develop command line programs.

As one of the most popular development tools, Node. js is a skill that Web developers should master to use it to develop command line programs.

The following is my extension tutorial Based on it. It should be the best solution at present.

1. executable scripts

Let's start with the simplest example.

First, use JavaScript to write an executable script hello.

#!/usr/bin/env nodeconsole.log('hello world');

Then, modify the hello permission.

$ chmod 755 hello

Now, hello can be executed.

$ ./hellohello world

If you want to remove the PATH before hello, you can add the PATH of hello to the environment variable PATH. However, another better way is to create package. json in the current directory and write the following content.

{ "name": "hello", "bin": {  "hello": "hello" }}

Then run the npm link command.

$ npm link

Now execute "hello", and you do not need to enter the path.

$ hellohello world

Ii. Original Syntax of command line parameters

Command line parameters can be obtained using the system variable process. argv.

The following is a script hello.

#!/usr/bin/env nodeconsole.log('hello ', process.argv[2]);

During execution, add parameters directly after the script file.

$ ./hello tomhello tom

In the above Code, the actual execution is node./hello tom, and the corresponding process. argv is ['node', '/path/to/hello', 'Tom'].

3. Create a process

The script can create a sub-process through the child_process module to execute Unix system commands.

#!/usr/bin/env nodevar 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);});

The usage is as follows.

$ ./hello tomhello tom

Iv. shelljs Module

The shelljs module repacks child_process, making it easier to call system commands. It must be installed before use.

npm install --save shelljs

Then, rewrite the script.

#!/usr/bin/env nodevar name = process.argv[2];var shell = require("shelljs");shell.exec("echo hello " + name);

The above code is the local mode of shelljs, that is, the shell command is executed through the exec method. In addition, the global mode allows you to directly write shell commands in the 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);}

V. yargs Module

Shelljs only addresses how to call shell commands, while the yargs module can address how to process command line parameters. It also needs to be installed.

$ npm install --save yargs

The yargs module provides an argv object for reading command line parameters. See the modified hello.

#!/usr/bin/env nodevar argv = require('yargs').argv;console.log('hello ', argv.name);

You can use either of the following methods.

$ hello --name=tomhello tom$ hello --name tomhello tom

That is to say, the original return value of process. argv is as follows.

$ node hello --name=tom[ 'node', '/path/to/myscript.js', '--name=tom' ]

Yargs can change the preceding result to an object. Each parameter is a key-value pair.

var argv = require('yargs').argv;// $ node hello --name=tom// argv = {//  name: tom// };

If you change argv. name To argv. n, you can use the short parameter format of a letter.

$ hello -n tomhello tom

You can use the alias method to specify the name as the alias of n.

#!/usr/bin/env nodevar argv = require('yargs') .alias('n', 'name') .argv;console.log('hello ', argv.n);

In this way, both short parameters and long parameters can be used.

$ hello -n tomhello tom$ hello --name tomhello tom

The argv object has an underscore (_) attribute to obtain parameters starting with a non-join line.

#!/usr/bin/env nodevar argv = require('yargs').argv;console.log('hello ', argv.n);console.log(argv._);

The usage is as follows.

$ hello A -n tom B Chello tom[ 'A', 'B', 'C' ]

Vi. Configure command line parameters

The yargs module also provides three methods for configuring command line parameters.

  1. Demand: Required
  2. Default: default Value
  3. Describe: Prompt
#!/usr/bin/env nodevar argv = require('yargs') .demand(['n']) .default({n: 'tom'}) .describe({n: 'your name'}) .argv;console.log('hello ', argv.n);

The n parameter specified in the Code above cannot be omitted. The default value is tom, and a prompt is displayed.

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

#!/usr/bin/env nodevar 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 need a value and only play a role in the switch. In this case, you can use the boolean method to specify these parameters to return a boolean value.

#!/usr/bin/env nodevar argv = require('yargs') .boolean(['n']) .argv;console.log('hello ', argv.n);

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

$ hellohello false$ hello -nhello true$ hello -n tomhello true

The boolean method can also be used as an attribute to write the option object.

#!/usr/bin/env nodevar argv = require('yargs') .option('n', {  boolean: true }) .argv;console.log('hello ', argv.n);

VII. Help Information

The yargs module provides the following methods to generate help information.

  1. Usage: Format
  2. Example: Provide examples
  3. Help: displays help information.
  4. Epilog: displays at the end of the help information.
#!/usr/bin/env nodevar 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 execution result is as follows.

$ hello -hUsage: hello [options]Options: -f, --name your name [string] [required] [default: "tom"] -h, --help Show help [boolean]Examples: hello -n tom say hello to Tomcopyright 2015

8. subcommands

The yargs module also allows you to set Git-style sub-commands using the command method.

#!/usr/bin/env nodevar 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);

The usage is as follows.

$ hello morning -n tomGood Morninghello tom

This function can be combined with the shellojs module.

#!/usr/bin/env noderequire('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 sub-command usually has its own parameters, which must be specified separately in the callback function. In the callback function, you must first reset the yargs object using the reset method.

#!/usr/bin/env noderequire('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;

The usage is as follows.

$ hello morning -m "Are you hungry?"Good MorningAre you hungry?

9. Other matters

(1) Return Value

According to Unix tradition, 0 is returned if the program is successfully executed; otherwise, 1 is returned.

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

(2) redirection

Unix allows programs to redirect data using pipelines.

$ ps aux | grep 'node'

The script can obtain redirected data by listening to standard input data events.

process.stdin.resume();process.stdin.setEncoding('utf8');process.stdin.on('data', function(data) { process.stdout.write(data);});

The following is the usage.

$ echo 'foo' | ./hellohello foo

(3) System Signal

The operating system can send signals to processes in progress, and the process object can listen to signal events.

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

The method for sending signals is as follows.

$ kill -s SIGINT [process_id]

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.