Node.js 命令列程式開發教程

阮一峰發表於2015-05-26


最近,Npm的網誌有一組系列文章,我覺得寫得非常好。下面就是我在它的基礎上擴充套件的教程,應該是目前最好的解決方案了。
一、可執行指令碼
我們從最簡單的講起。
首先,使用 JavaScript 語言,寫一個可執行指令碼 hello 。
#!/usr/bin/env node
console.log('hello world');
然後,修改 hello 的許可權。
$ chmod 755 hello
現在,hello 就可以執行了。
$ ./hello
hello world
如果想把 hello 前面的路徑去除,可以將 hello 的路徑加入環境變數 PATH。但是,另一種更好的做法,是在當前目錄下新建 package.json ,寫入下面的內容。
{
  "name": "hello",
  "bin": {
    "hello": "hello"
  }
}
然後執行 npm link 命令。
$ npm link
現在再執行 hello ,就不用輸入路徑了。
$ hello
hello world
二、命令列引數的原始寫法
命令列引數可以用系統變數 process.argv 獲取。
#!/usr/bin/env node
console.log('hello ', process.argv[2]);
執行時,直接在指令碼檔案後面,加上引數即可。
$ ./hello tom
hello tom
三、新建程式
指令碼可以通過 child_process 模組新建子程式,從而執行 Unix 系統命令。
#!/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,呼叫系統命令更加方便。它需要安裝後使用。
npm install --save shelljs
然後,改寫指令碼。
#!/usr/bin/env node
var name = process.argv[2];
var shell = require("shelljs");

shell.exec("echo hello " + name);
上面程式碼是 shelljs 的本地模式,即通過 exec 方法執行 shell 命令。此外還有全域性模式,允許直接在指令碼中寫 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 只解決了如何呼叫 shell 命令,而 yargs 模組能夠解決如何處理命令列引數。它也需要安裝。
$ npm install --save yargs
yargs 模組提供 argv 物件,用來讀取命令列引數。請看改寫後的 hello 。
#!/usr/bin/env node
var argv = require('yargs').argv;

console.log('hello ', argv.name);
使用時,下面兩種用法都可以。
$ hello --name=tom
hello tom

$ hello --name tom
hello tom
如果將 argv.name 改成 argv.n,就可以使用一個字母的短引數形式了。
$ 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);
這樣一來,短引數和長引數就都可以使用了。
$ hello -n tom
hello tom
$ hello --name tom
hello tom
argv 物件有一個下劃線(_)屬性,可以獲取非連詞線開頭的引數。
#!/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' ]
六、命令列引數的配置
yargs 模組還提供3個方法,用來配置命令列引數。
  • demand:是否必選
  • default:預設值
  • 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 引數不可省略,預設值為 tom,並給出一行提示。
options 方法允許將所有這些配置寫進一個物件。
#!/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);
有時,某些引數不需要值,只起到一個開關作用,這時可以用 boolean 方法指定這些引數返回布林值。
#!/usr/bin/env node
var argv = require('yargs')
  .boolean(['n'])
  .argv;

console.log('hello ', argv.n);
上面程式碼中,引數 n 總是返回一個布林值,用法如下。
$ hello
hello  false
$ hello -n
hello  true
$ hello -n tom
hello  true
boolean 方法也可以作為屬性,寫入 option 物件。
#!/usr/bin/env node
var argv = require('yargs')
  .option('n', {
    boolean: true
  })
  .argv;

console.log('hello ', argv.n);
七、幫助資訊
yargs 模組提供以下方法,生成幫助資訊。
  • usage:用法格式
  • example:提供例子
  • help:顯示幫助資訊
  • epilog:出現在幫助資訊的結尾
#!/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);
執行結果如下。
$ 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 模組還允許通過 command 方法,設定 Git 風格的子命令。
#!/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
可以將這個功能與 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);
每個子命令往往有自己的引數,這時就需要在回撥函式中單獨指定。回撥函式中,要先用 reset 方法重置 yargs 物件。
#!/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?
九、其他事項
(1)返回值
根據 Unix 傳統,程式執行成功返回 0,否則返回 1 。
if (err) {
  process.exit(1);
} else {
  process.exit(0);
}
(2)重定向
Unix 允許程式之間使用管道重定向資料。
$ ps aux | grep 'node'
指令碼可以通過監聽標準輸入的data 事件,獲取重定向的資料。
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(data) {
  process.stdout.write(data);
});
下面是用法:
$ echo 'foo' | ./hello
hello foo
(3)系統訊號
作業系統可以向執行中的程式傳送訊號,process 物件能夠監聽訊號事件。
process.on('SIGINT', function () {
  console.log('Got a SIGINT');
  process.exit(0);
});
傳送訊號的方法如下。
$ kill -s SIGINT [process_id]
評論(1)

相關文章