使用 Node.js 构建交互式 CLI

使用 Node.js 构建一个命令行界面,根据您的需求创建一个文件。
255 位读者喜欢这篇文章。
Programming keyboard.

Opensource.com

Node.js 在构建命令行界面 (CLI) 方面非常有用。 在本文中,我将教您如何使用 Node.js 构建一个 CLI,该 CLI 会提出一些问题并根据答案创建一个文件。

NodeJS CLI output

开始吧

首先,创建一个全新的 npm 包。(Npm 是 JavaScript 包管理器。)

mkdir my-script
cd my-script
npm init

Npm 会问一些问题。 之后,我们需要安装一些包。

npm install --save chalk figlet inquirer shelljs

以下是这些包的作用

  • Chalk: 正确完成的终端字符串样式
  • Figlet: 一种使用普通文本制作大字母的程序
  • Inquirer: 常见的交互式命令行用户界面的集合
  • ShellJS: Node.js 的便携式 Unix shell 命令

创建一个 index.js 文件

现在,我们将创建一个带有以下内容的 index.js 文件

#!/usr/bin/env node

const inquirer = require("inquirer");
const chalk = require("chalk");
const figlet = require("figlet");
const shell = require("shelljs");

规划 CLI

在编写任何代码之前,最好先规划 CLI 需要做什么。 这个 CLI 只做一件事:创建一个文件

CLI 将询问两个问题——文件名是什么?扩展名是什么?——然后创建文件,并显示一条带有已创建文件路径的成功消息。

// index.js

const run = async () => {
  // show script introduction
  // ask questions
  // create the file
  // show success message
};

run();

第一个函数是脚本介绍。 让我们使用 chalkfiglet 来完成这项工作。

const init = () => {
  console.log(
    chalk.green(
      figlet.textSync("Node JS CLI", {
        font: "Ghost",
        horizontalLayout: "default",
        verticalLayout: "default"
      })
    )
  );
}

const run = async () => {
  // show script introduction
  init();

  // ask questions
  // create the file
  // show success message
};

run();

其次,我们将编写一个提出问题的函数。

const askQuestions = () => {
  const questions = [
    {
      name: "FILENAME",
      type: "input",
      message: "What is the name of the file without extension?"
    },
    {
      type: "list",
      name: "EXTENSION",
      message: "What is the file extension?",
      choices: [".rb", ".js", ".php", ".css"],
      filter: function(val) {
        return val.split(".")[1];
      }
    }
  ];
  return inquirer.prompt(questions);
};

// ...

const run = async () => {
  // show script introduction
  init();

  // ask questions
  const answers = await askQuestions();
  const { FILENAME, EXTENSION } = answers;

  // create the file
  // show success message
};

请注意来自 inquirer 的常量 FILENAME 和 EXTENSIONS。

下一步将创建文件。

const createFile = (filename, extension) => {
  const filePath = `${process.cwd()}/${filename}.${extension}`
  shell.touch(filePath);
  return filePath;
};

// ...

const run = async () => {
  // show script introduction
  init();

  // ask questions
  const answers = await askQuestions();
  const { FILENAME, EXTENSION } = answers;

  // create the file
  const filePath = createFile(FILENAME, EXTENSION);

  // show success message
};

最后但并非最不重要的一点是,我们将显示成功消息以及文件路径。

const success = (filepath) => {
  console.log(
    chalk.white.bgGreen.bold(`Done! File created at ${filepath}`)
  );
};

// ...

const run = async () => {
  // show script introduction
  init();

  // ask questions
  const answers = await askQuestions();
  const { FILENAME, EXTENSION } = answers;

  // create the file
  const filePath = createFile(FILENAME, EXTENSION);

  // show success message
  success(filePath);
};

让我们通过运行 node index.js 来测试脚本。 这是我们得到的

NodeJS CLI output

完整代码

这是最终代码

#!/usr/bin/env node

const inquirer = require("inquirer");
const chalk = require("chalk");
const figlet = require("figlet");
const shell = require("shelljs");

const init = () => {
  console.log(
    chalk.green(
      figlet.textSync("Node JS CLI", {
        font: "Ghost",
        horizontalLayout: "default",
        verticalLayout: "default"
      })
    )
  );
};

const askQuestions = () => {
  const questions = [
    {
      name: "FILENAME",
      type: "input",
      message: "What is the name of the file without extension?"
    },
    {
      type: "list",
      name: "EXTENSION",
      message: "What is the file extension?",
      choices: [".rb", ".js", ".php", ".css"],
      filter: function(val) {
        return val.split(".")[1];
      }
    }
  ];
  return inquirer.prompt(questions);
};

const createFile = (filename, extension) => {
  const filePath = `${process.cwd()}/${filename}.${extension}`
  shell.touch(filePath);
  return filePath;
};

const success = filepath => {
  console.log(
    chalk.white.bgGreen.bold(`Done! File created at ${filepath}`)
  );
};

const run = async () => {
  // show script introduction
  init();

  // ask questions
  const answers = await askQuestions();
  const { FILENAME, EXTENSION } = answers;

  // create the file
  const filePath = createFile(FILENAME, EXTENSION);

  // show success message
  success(filePath);
};

run();

在任何地方使用该脚本

要在任何地方执行此脚本,请在 package.json 文件中添加一个 bin 部分,然后运行 npm link

{
  "name": "creator",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "chalk": "^2.4.1",
    "figlet": "^1.2.0",
    "inquirer": "^6.0.0",
    "shelljs": "^0.8.2"
  },
  "bin": {
    "creator": "./index.js"
  }
}

运行 npm link 使此脚本在任何地方都可用。

这是运行此命令时发生的情况

/usr/bin/creator -> /usr/lib/node_modules/creator/index.js
/usr/lib/node_modules/creator -> /home/hugo/code/creator

它将 index.js 文件链接为可执行文件。 这只有在 CLI 脚本的第一行时才有可能:#!/usr/bin/env node

现在我们可以通过调用来运行此脚本

$ creator

总结

如您所见,Node.js 使构建出色的命令行工具变得非常容易! 如果您想更进一步,请查看其他软件包

  • meow – 一个简单的命令行助手
  • yargs – 一个命令行选项字符串解析器
  • pkg – 将您的 Node.js 项目打包成一个可执行文件

在评论中告诉我们您构建 CLI 的经验。

标签
User profile image.
软件工程师 - Github

评论已关闭。

Creative Commons License本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。
© . All rights reserved.