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