发布于 2026-01-06 6 阅读
0

构建你的第一个交互式 Node.js CLI

构建你的第一个交互式 Node.js CLI

原文发布于我的博客

在构建命令行界面(也称为 CLI)时,NodeJS 非常有用。

在这篇文章中,我将教你如何构建一个命令行界面,它会询问一些问题,并根据答案创建一个文件。

入门

让我们从创建一个全新的 npm 包开始。

mkdir my-script
cd my-script
npm init
Enter fullscreen mode Exit fullscreen mode

NPM会询问一些问题。之后,我们需要安装一些软件包。

npm install --save chalk figlet inquirer shelljs
Enter fullscreen mode Exit fullscreen mode

这些软件包的功能:

  • 粉笔——终端字符串样式正确
  • Figlet ——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");
Enter fullscreen mode Exit fullscreen mode

规划 CLI

在编写任何代码之前,最好先规划好 CLI 需要执行的操作。

这个 CLI 只会做一件事:创建一个文件

它应该会询问几个问题,然后显示一条成功消息,其中包含创建的文件路径。

问题是:文件名是什么?文件扩展名是什么?

// index.js

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

run();
Enter fullscreen mode Exit fullscreen mode

第一个函数是脚本导入。让我们使用chalkfiglet来完成任务。


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

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

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

run();
Enter fullscreen mode Exit fullscreen mode

现在该编写一个提问函数了。

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
};
Enter fullscreen mode Exit fullscreen mode

注意来自以下来源的常量 FILENAME 和 EXTENSIONS inquirer

下一步是创建文件。

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

Enter fullscreen mode Exit fullscreen mode

最后,显示成功消息以及文​​件路径。

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);
};
Enter fullscreen mode Exit fullscreen mode

让我们运行脚本来测试一下node index.js

截屏

太棒了!以下是最终代码:

最终代码

#!/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 f*cking JS", {
        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();
Enter fullscreen mode Exit fullscreen mode

要在任何地方执行此脚本,请在文件中添加一个 bin 部分package.json并运行。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"
  }
}

Enter fullscreen mode Exit fullscreen mode
$ npm link
$ creator
Enter fullscreen mode Exit fullscreen mode

希望对您有所帮助 :)


照片由 Alex Knight 拍摄,来自 Unsplash

文章来源:https://dev.to/hugodias/building-your-first-interactive-node-js-cli-1g2c