Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Nodejs command-line program development tutorial     - How to install and use the malware detection tool LMD and ClamAV antivirus engine on Linux (Linux)

- Add a custom encryption algorithm in OpenSSL (Linux)

- Linux Samba server-side structures and the use of the client (Server)

- How to modify the Emacs Major Mode Shortcuts (Linux)

- Vim plugin installation YouCompleteMe (Linux)

- Cooling solutions Ubuntu system (Linux)

- Linux, Chrome browser font settings beautification (Linux)

- MySQL replication master and slave structure built (Database)

- Partition contrast manifestations under Windows and Linux (Linux)

- Installation image conversion tool on your Ubuntu Converseen 0.8.1 (Linux)

- using the ssh command to check the socket / Network Connections (Linux)

- How to Set Free SSH password on CentOS / RHEL (Linux)

- Oracle Migration partition table (Database)

- DRBD rapid installation and deployment (Server)

- Linux text processing tool of sed (Linux)

- CentOS7 installation GAMIT and GMT (Linux)

- Struts2 form of non-use component tags (Programming)

- Security: set limits on password (Linux)

- How to install Ubuntu California - the calendar application (Linux)

- Linux automatically install service components and optimize the kernel parameters (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:      
 
- Android Fragment everything you need to know (Programming)
- MySQL Tutorial: Philosophical Reflections on the unauthenticated user (Database)
- Why everybody ought to know LLVM (Linux)
- C ++ 11 smart pointers (Programming)
- Oracle SDE and maintain common commands - Display space (Database)
- pkg-config to use (Linux)
- How to create a someone project on github (Linux)
- The multiplexed signal driving IO (Programming)
- Restrict console access to Linux servers to improve security (Linux)
- Delay for the specified IP port analog network to send and receive packets on Linux (Linux)
- Java Performance Tuning the proxy mode (Programming)
- In Spring AOP example explanation (Programming)
- UUID in Java (Programming)
- Spark and Hadoop comparison (Server)
- Postgres-X2 deployment steps (Database)
- Linux operating process information (Linux)
- Workaround CentOS error message during compilation PHP5 common (Linux)
- A detailed introduction to the Hadoop ecosystem (Server)
- After Pydev installation, Eclipse does not display solutions (Linux)
- Redis data types Introduction (Database)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.