欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

开发一个简单的nodejs版CLI(命令行)工具

程序员文章站 2022-07-15 16:27:03
...

原文链接

项目初始化

通过npm命令初始化项目

mkdir my-script
cd my-script
npm init

一路enter后,添加如下依赖

npm install --save chalk figlet inquirer shelljs

相关依赖说明:

  • chalk  —  美化终端字符显示
  • figlet  —  在终端输出大型字符
  • inquirer  —  命令行参数输入交互
  • shelljs  —  平台相关命令

index.js

在当前目录下创建index.js文件

#!/usr/bin/env node

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

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

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

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

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 init = () => {
  console.log(
    chalk.green(
      figlet.textSync("CLI", {
        font: "Ghost",
        horizontalLayout: "default",
        verticalLayout: "default"
      })
    )
  );
};

run();

全局化脚本

要想该脚本可在命令行使用,需要在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"
  }
}

运行npm link,可以看到类似输出

d:\.npm\creator -> d:\.npm\node_modules\my-script\index.js
d:\.npm\node_modules\my-script -> E:\workspace-nodejs\my-script

表示该脚本已被链接,只要确保环境变量node可用便可在命令行使用了

$ creator

脚本的卸载

npm rm --global creator
npm uninstall --global my-script

未知: npm unlink creator

转载于:https://www.jianshu.com/p/acf2e7ec42b8