Node.js 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 theNode.jsprocess
    [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
 */

// 将第一个参数存储为用户名。
var username = process.argv[2];

// 检查是否未提供用户名。
if (!username) {

    // 提取文件名
    var appName = process.argv[1].split(require('path').sep).pop();

    //  给用户一个有关如何使用该应用程序的示例。
    console.error('Missing argument! Example: %s YOUR_NAME', appName);

    // 退出应用程序(成功:0,错误:1)。 
    //错误将停止执行链。例如:
    //   ./app.js && ls       -> won't execute ls
    //   ./app.js David && ls -> will execute ls
    process.exit(1);
}

// 将消息打印到控制台。
console.log('Hello %s!', username);