Hello World 命令列

Node.js 也可用於建立命令列實用程式。下面的示例從命令列讀取第一個引數並列印 Hello 訊息。

要在 Unix 系統上執行此程式碼:

  1. 建立一個新檔案並貼上下面的程式碼。檔名無關緊要。
  2. 使用 chmod 700 FILE_NAME 使該檔案可執行
  3. 使用 ./APP_NAME David 執行應用程式

在 Windows 上,你執行步驟 1 並使用 node APP_NAME David 執行它

#!/usr/bin/env node

'use strict';

/*
    The command line arguments are stored in the `process.argv` array, 
    which has the following structure:
    [0] The path of the executable that started the Node.js process
    [1] The path to this application
    [2-n] the command line arguments

    Example: [ '/bin/node', '/path/to/yourscript', 'arg1', 'arg2', ... ]
    src: https://nodejs.org/api/process.html#process_process_argv
 */

// Store the first argument as username.
var username = process.argv[2];

// Check if the username hasn't been provided.
if (!username) {

    // Extract the filename
    var appName = process.argv[1].split(require('path').sep).pop();

    //  Give the user an example on how to use the app.
    console.error('Missing argument! Example: %s YOUR_NAME', appName);

    // Exit the app (success: 0, error: 1). 
    // An error will stop the execution chain. For example:
    //   ./app.js && ls       -> won't execute ls
    //   ./app.js David && ls -> will execute ls
    process.exit(1);
}

// Print the message to the console.
console.log('Hello %s!', username);