最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解Node.js 命令行程序開(kāi)發(fā)教程

 更新時(shí)間:2017年06月07日 14:59:31   作者:阮一峰  
一種編程語(yǔ)言是否易用,很大程度上,取決于開(kāi)發(fā)命令行程序的能力。本篇文章主要介紹了Node.js 命令行程序開(kāi)發(fā)教程,有興趣的可以了解一下

一種編程語(yǔ)言是否易用,很大程度上,取決于開(kāi)發(fā)命令行程序的能力。

Node.js 作為目前最熱門(mén)的開(kāi)發(fā)工具之一,怎樣使用它開(kāi)發(fā)命令行程序,是 Web 開(kāi)發(fā)者應(yīng)該掌握的技能。

下面就是我在它的基礎(chǔ)上擴(kuò)展的教程,應(yīng)該是目前最好的解決方案了。

一、可執(zhí)行腳本

我們從最簡(jiǎn)單的講起。

首先,使用 JavaScript 語(yǔ)言,寫(xiě)一個(gè)可執(zhí)行腳本 hello 。

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

然后,修改 hello 的權(quán)限。

$ chmod 755 hello

現(xiàn)在,hello 就可以執(zhí)行了。

$ ./hello
hello world

如果想把 hello 前面的路徑去除,可以將 hello 的路徑加入環(huán)境變量 PATH。但是,另一種更好的做法,是在當(dāng)前目錄下新建 package.json ,寫(xiě)入下面的內(nèi)容。

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

然后執(zhí)行 npm link 命令。

$ npm link

現(xiàn)在再執(zhí)行 hello ,就不用輸入路徑了。

$ hello
hello world

二、命令行參數(shù)的原始寫(xiě)法

命令行參數(shù)可以用系統(tǒng)變量 process.argv 獲取。

下面是一個(gè)腳本 hello 。

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

執(zhí)行時(shí),直接在腳本文件后面,加上參數(shù)即可。

$ ./hello tom
hello tom

上面代碼中,實(shí)際上執(zhí)行的是 node ./hello tom ,對(duì)應(yīng)的 process.argv 是 ['node', '/path/to/hello', 'tom'] 。

三、新建進(jìn)程

腳本可以通過(guò) child_process 模塊新建子進(jìn)程,從而執(zhí)行 Unix 系統(tǒng)命令。

#!/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);
});

用法如下。

$ ./hello tom
hello tom

四、shelljs 模塊

shelljs 模塊重新包裝了 child_process,調(diào)用系統(tǒng)命令更加方便。它需要安裝后使用。

npm install --save shelljs

然后,改寫(xiě)腳本。

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

shell.exec("echo hello " + name);

上面代碼是 shelljs 的本地模式,即通過(guò) exec 方法執(zhí)行 shell 命令。此外還有全局模式,允許直接在腳本中寫(xiě) shell 命令。

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);
}

五、yargs 模塊

shelljs 只解決了如何調(diào)用 shell 命令,而 yargs 模塊能夠解決如何處理命令行參數(shù)。它也需要安裝。

$ npm install --save yargs

yargs 模塊提供 argv 對(duì)象,用來(lái)讀取命令行參數(shù)。請(qǐng)看改寫(xiě)后的 hello 。

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

console.log('hello ', argv.name);

使用時(shí),下面兩種用法都可以。

$ hello --name=tom
hello tom

$ hello --name tom
hello tom

也就是說(shuō),process.argv 的原始返回值如下。

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

yargs 可以上面的結(jié)果改為一個(gè)對(duì)象,每個(gè)參數(shù)項(xiàng)就是一個(gè)鍵值對(duì)。

var argv = require('yargs').argv;

// $ node hello --name=tom
// argv = {
//  name: tom
// };

如果將 argv.name 改成 argv.n,就可以使用一個(gè)字母的短參數(shù)形式了。

$ hello -n tom
hello tom

可以使用 alias 方法,指定 name 是 n 的別名。

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

console.log('hello ', argv.n);

這樣一來(lái),短參數(shù)和長(zhǎng)參數(shù)就都可以使用了。

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

argv 對(duì)象有一個(gè)下劃線(_)屬性,可以獲取非連詞線開(kāi)頭的參數(shù)。

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

console.log('hello ', argv.n);
console.log(argv._);

用法如下。

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

六、命令行參數(shù)的配置

yargs 模塊還提供3個(gè)方法,用來(lái)配置命令行參數(shù)。

  1. demand:是否必選
  2. default:默認(rèn)值
  3. describe:提示
#!/usr/bin/env node
var argv = require('yargs')
 .demand(['n'])
 .default({n: 'tom'})
 .describe({n: 'your name'})
 .argv;

console.log('hello ', argv.n);

上面代碼指定 n 參數(shù)不可省略,默認(rèn)值為 tom,并給出一行提示。

options 方法允許將所有這些配置寫(xiě)進(jìn)一個(gè)對(duì)象。

#!/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);

有時(shí),某些參數(shù)不需要值,只起到一個(gè)開(kāi)關(guān)作用,這時(shí)可以用 boolean 方法指定這些參數(shù)返回布爾值。

#!/usr/bin/env node
var argv = require('yargs')
 .boolean(['n'])
 .argv;

console.log('hello ', argv.n);

上面代碼中,參數(shù) n 總是返回一個(gè)布爾值,用法如下。

$ hello
hello false
$ hello -n
hello true
$ hello -n tom
hello true

boolean 方法也可以作為屬性,寫(xiě)入 option 對(duì)象。

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

console.log('hello ', argv.n);

七、幫助信息

yargs 模塊提供以下方法,生成幫助信息。

  1. usage:用法格式
  2. example:提供例子
  3. help:顯示幫助信息
  4. epilog:出現(xiàn)在幫助信息的結(jié)尾
#!/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);

執(zhí)行結(jié)果如下。

$ 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

八、子命令

yargs 模塊還允許通過(guò) command 方法,設(shè)置 Git 風(fēng)格的子命令。

#!/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);

用法如下。

$ hello morning -n tom
Good Morning
hello tom

可以將這個(gè)功能與 shellojs 模塊結(jié)合起來(lái)。

#!/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);

每個(gè)子命令往往有自己的參數(shù),這時(shí)就需要在回調(diào)函數(shù)中單獨(dú)指定?;卣{(diào)函數(shù)中,要先用 reset 方法重置 yargs 對(duì)象。

#!/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;

用法如下。

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

九、其他事項(xiàng)

(1)返回值

根據(jù) Unix 傳統(tǒng),程序執(zhí)行成功返回 0,否則返回 1 。

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

(2)重定向

Unix 允許程序之間使用管道重定向數(shù)據(jù)。

$ ps aux | grep 'node'

腳本可以通過(guò)監(jiān)聽(tīng)標(biāo)準(zhǔn)輸入的data 事件,獲取重定向的數(shù)據(jù)。

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

下面是用法。

$ echo 'foo' | ./hello
hello foo

(3)系統(tǒng)信號(hào)

操作系統(tǒng)可以向執(zhí)行中的進(jìn)程發(fā)送信號(hào),process 對(duì)象能夠監(jiān)聽(tīng)信號(hào)事件。

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

發(fā)送信號(hào)的方法如下。

$ kill -s SIGINT [process_id]

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • node版本切換與版本升級(jí)降級(jí)教程(win)

    node版本切換與版本升級(jí)降級(jí)教程(win)

    nvm是一個(gè)node的版本管理工具,可以簡(jiǎn)單操作node版本的切換、安裝、查看,下面這篇文章主要給大家介紹了關(guān)于node版本切換與版本升級(jí)降級(jí)教程的相關(guān)資料,需要的朋友可以參考下
    2022-11-11
  • Node.js與Sails redis組件的使用教程

    Node.js與Sails redis組件的使用教程

    這篇文章主要介紹了Node.js與Sails redis組件的使用教程,主要介紹幾個(gè)用法,為string,set,hash和list的使用。需要的朋友可以參考下
    2017-02-02
  • 詳解Node.js實(shí)現(xiàn)301、302重定向服務(wù)

    詳解Node.js實(shí)現(xiàn)301、302重定向服務(wù)

    這篇文章主要介紹了詳解Node.js實(shí)現(xiàn)301、302重定向服務(wù),詳細(xì)的介紹了用Nodejs的http模塊,實(shí)現(xiàn)一個(gè)301或302重定服務(wù)。
    2017-04-04
  • Node.js實(shí)現(xiàn)大文件斷點(diǎn)續(xù)傳示例詳解

    Node.js實(shí)現(xiàn)大文件斷點(diǎn)續(xù)傳示例詳解

    這篇文章主要為大家介紹了Node.js實(shí)現(xiàn)大文件斷點(diǎn)續(xù)傳示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • mac上node.js環(huán)境的安裝測(cè)試

    mac上node.js環(huán)境的安裝測(cè)試

    這篇文章主要為大家詳細(xì)介紹了mac上node.js環(huán)境的安裝測(cè)試,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-07-07
  • Node.js事件的正確使用方法

    Node.js事件的正確使用方法

    這篇文章主要給大家介紹了關(guān)于Node.js事件的正確使用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Node.js具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • node.js中Buffer緩沖器的原理與使用方法分析

    node.js中Buffer緩沖器的原理與使用方法分析

    這篇文章主要介紹了node.js中Buffer緩沖器的原理與使用方法,結(jié)合實(shí)例形式分析了node.js Buffer緩沖器的基本概念、原理、創(chuàng)建、使用方法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下
    2019-11-11
  • vscode無(wú)法運(yùn)行npm命令的問(wèn)題解決(cmd可行)

    vscode無(wú)法運(yùn)行npm命令的問(wèn)題解決(cmd可行)

    本文主要介紹了vscode無(wú)法運(yùn)行npm命令的問(wèn)題解決(cmd可行),VSCode無(wú)法調(diào)用npm可能是因?yàn)榄h(huán)境路徑配置錯(cuò)誤,下面就來(lái)具體介紹一下原因及解決方法,感興趣的可以了解一下
    2024-04-04
  • node版本管理工具n包使用教程詳解

    node版本管理工具n包使用教程詳解

    這篇文章主要介紹了node版本管理工具n包使用教程詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-11-11
  • node.js使用require()函數(shù)加載模塊

    node.js使用require()函數(shù)加載模塊

    本文通過(guò)幾個(gè)具體實(shí)例來(lái)分析node.js中使用require()函數(shù)來(lái)加載模塊的方法。非常的詳盡,給需要的小伙伴們參考下吧
    2014-11-11

最新評(píng)論

孟州市| 赞皇县| 交城县| 锡林郭勒盟| 沂水县| 德令哈市| 碌曲县| 四子王旗| 怀来县| 玛纳斯县| 古蔺县| 盐亭县| 齐河县| 孝义市| 梁山县| 普陀区| 定襄县| 西昌市| 金寨县| 阿图什市| 五华县| 五寨县| 涪陵区| 阳信县| 诸暨市| 宝兴县| 光山县| 夏河县| 虹口区| 祁东县| 永宁县| 长海县| 建宁县| 泗阳县| 潮州市| 合阳县| 蓬莱市| 托里县| 商都县| 高台县| 阿克陶县|