Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Nodejs command-line program development tutorial     - Linux serial port driver test (Linux)

- Oracle ordinary users show parameter method (Database)

- Java data structures - the single linked list LinkedList linear table (Programming)

- On Android running ClojureScript (Linux)

- Run two MySQL service on one server (Database)

- iostat command Detailed (Linux)

- RocketMQ Message Queuing simple deployment (Linux)

- Linux Creating a new user error Creating mailbox file: File exists (Linux)

- Install KVM on Ubuntu and build a virtual environment (Linux)

- Tomcat session clustering and server session (Server)

- Three kinds of binary tree traversal recursive and iterative solution (Programming)

- map and hash_map STL containers (Programming)

- Dom4j change XML coding (Programming)

- C ++ function object (Programming)

- Features and prevention methods elaborate network security grayware (Linux)

- Incremental garbage collection mechanism for Ruby 2.2 (Programming)

- CentOS7 virtual machine starts appear Permission denied (Linux)

- How to query the role of Linux services (Linux)

- How to avoid two Chrome icon appears in ELementary OS Freya (Linux)

- FreeRadius installation process record (Linux)

 
         
  Nodejs command-line program development tutorial
     
  Add Date : 2017-04-13      
         
       
         
  A programming language is easy to use, to a large extent, it depends on the ability to develop command-line program.

Node.js as one of the most popular development tools, how to use it to develop command-line program, is a Web developer should master the skills.

Recently, Npm blog has a series of articles, I thought that it was very good. Here is what I extended it on the basis of course, should be the best solution for the.

First, an executable script

We start from the most simple.

First, use the JavaScript language, write a script executable hello.

#! / Usr / bin / env node
console.log ( 'hello world');
Then, modify the permissions hello.

$ Chmod 755 hello
Now, hello you can be executed.

$ ./hello
hello world
If you want to remove the path in front of hello, hello can be added to the path environment variable PATH. However, another a better approach is to create a new package.json in the current directory, write the following.

{
"Name": "hello",
"Bin": {
"Hello": "hello"
}
}
Then execute the command npm link.

$ Npm link
Now and then execute hello, do not enter a path.

$ Hello
hello world
Second, the wording of the original command-line arguments

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

#! / Usr / bin / env node
console.log ( 'hello', process.argv [2]);
When executed, the script file directly in the back, plus parameters.

$ ./hello Tom
hello tom
Third, the new process

Script can create a child process by child_process modules to execute commands on Unix systems.

#! / Usr / bin / env node
var name = process.argv [2];
varexec = 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

shelljs module repackaged child_process, call the system command more convenient. It needs to be used after installation.

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 above code shelljs local mode, that execute shell commands via exec method. There are also global mode, allowing direct command shell written 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);
}
Five, yargs module

shelljs addressed only how to call shell commands, yargs module can resolve how to deal with command line arguments. It also needs to be installed.

$ Npm install --save yargs
yargs module provides argv object used to read command line parameters. See hello rewritten.

#! / Usr / bin / env node
var argv = require ( 'yargs') argv.;
console.log ( 'hello', argv.name);
When used, the following two uses can be.

$ Hello --name = tom
hello tom
$ Hello --name tom
hello tom
If argv.name into argv.n, you can use a short form letter of the parameters.

$ Hello -n tom
hello tom
You can use the alias method to specify the name is an alias n.

#! / Usr / bin / env node
var argv = require ( 'yargs')
.alias ( 'n', 'name')
.argv;
console.log ( 'hello', argv.n);
As a result, the parameters short and long-parameters can be used.

$ Hello -n tom
hello tom
$ Hello --name tom
hello tom
argv object has an underscore (_) attributes, you can get a non-parametric conjunctions line beginning.

#! / 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']
Sixth, the configuration command-line arguments

yargs module also provides three methods to configure the command line parameters.

demand: Are Required
default: Default
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 n parameter can not be omitted, the default is tom, and gives tips line.

All of these options allows to configure written 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, the value of certain parameters is not required, only play the role of a switch, then you can specify these parameters using the boolean method returns a Boolean value.

#! / Usr / bin / env node
var argv = require ( 'yargs')
.boolean ([ 'n'])
.argv;
console.log ( 'hello', argv.n);
The above code, the parameter n always returns a Boolean value, is used as follows.

$ Hello
hello false
$ Hello -n
hello true
$ Hello -n tom
hello true
boolean method can also be used as property write option object.

#! / Usr / bin / env node
var argv = require ( 'yargs')
.option ( 'n', {
boolean: true
})
.argv;
console.log ( 'hello', argv.n);
VII Help

yargs module provides the following methods to help generate information.

usage: Usage format
example: provide examples
help: Display help information
epilog: help message appears in the end
#! / 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);
Execution results 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
Eight sub-command

yargs module also allows command method, set the style Git subcommand.

#! / 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
GoodMorning
hello tom
This function module can be combined shellojs.

#! / 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 sub-command often have their own parameters, then you need to specify a separate callback function. Callback function, first with a reset method to reset yargs object.

#! / 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?"
GoodMorning
Are you hungry?
Other matters

(1) Return Value

According Unix tradition, the program execution returns 0 on success, 1 otherwise.

if (err) {
process.exit (1);
} Else {
process.exit (0);
}
(2) redirection

Unix allows the use of the pipeline to redirect data between programs.

$ Ps aux | grep 'node'
Your script can monitor the standard input event data, access to data redirection.

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 a signal to the execution process, process objects can listen for a signal event.

process.on ( 'SIGINT', function () {
console.log ( 'Got a SIGINT');
process.exit (0);
});
Transmission signal is as follows.

$ Kill -s SIGINT [process_id]
     
         
       
         
  More:      
 
- MySQL master-slave delay problem (Database)
- Formatting Java floating-point types (Programming)
- Fedora network set up simple (Linux)
- CentOS6.0 successful installation and configuration OpenCV (Linux)
- Ubuntu install video conversion tool Selene (Linux)
- Based shell: using read, the command-line script to achieve mass participation and input two integer calculation (Programming)
- Go Languages Reviews (Programming)
- Installation and use the telnet command under CentOS 6.x (Linux)
- MySQL partition table Comments (Database)
- Linux Apache server configure to protect system security (Linux)
- Linux iostat command example explanation (Linux)
- Linux environment RabbitMQ installation and monitoring of plug-in installation (Linux)
- Linux startup and logon security settings (Linux)
- TNS-03505 name could not be resolved (Database)
- Vi syntax highlighting settings (Linux)
- Linux learning portal: CentOS 6.4 system kernel upgrade (Linux)
- Those things packaged using Gradle to Android (Programming)
- Getting Started with Linux: CentOS7 Install Mono with the yum command (Server)
- map and hash_map STL containers (Programming)
- MySQL multi-master-slave synchronization (Database)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.