我们来开发一个下载仓库代码,并通过命令行界面来启动项目的功能
准备工作
安装以下工具,注意版本
1clear: 清屏2chalk: 装饰作用,使之终端上的输出加上颜色3figlet: 将字母转化为字符拼成的文字4git-pull-or-clone:将代码下载5inquirer: 在命令行中打出交互式的命令6ora: 优雅的显示loading效果
编码
1const { resolve } = require("path");2const fs = require("fs");3const { promisify } = require("util");4const chalk = require("chalk");5const inquirer = require("inquirer");6const figlet = require("figlet");7const clear = require("clear");8const ora = require("ora");9const download = promisify(require("git-pull-or-clone"));10const { spawn, log } = require("./utils");1112//仓库地址13const repo = "git@github.com:yuanguandong/react-keyevent.git";1415//清屏16clear();17//打印logo18log(19 figlet.textSync("WIDGET", {20 horizontalLayout: "fitted",21 verticalLayout: "default",22 width: 80,23 whitespaceBreak: true,24 }),25 "green"26);2728//主流程29const main = async () => {30 // 项⽬名称31 const answer = await inquirer.prompt([32 {33 type: "input",34 message: "DirName:",35 name: "name",36 default: "widgets", // 默认值37 },38 ]);39 const dir = resolve(`./${answer.name}`);40 const process = ora(chalk["gray"](`${dir} loading.....`));41 process.start();42 try {43 await download(repo, dir);44 process.succeed();45 log(`✅ Download Success`);46 } catch (e) {47 log(e, "red");48 process.fail();49 }50 tool(answer.name, dir);51};5253//工具方法54const actions = {55 install: async ({ dir, name }) => {56 log("installing....", "gray");57 await spawn("pnpm", ["install"], { cwd: `${name}/` });58 log("✅ Installed");59 },60 run: async ({ dir, name }) => {61 const isFile = fs.existsSync(`${dir}/node_modules`);62 if (isFile) {63 const res = await spawn("pnpm", ["run", "test"], { cwd: `${name}/` });64 return;65 } else {66 log("Not Installed", "red");67 }68 },69 exit: async ({ dir, name }) => {70 const isFile = fs.existsSync(`${dir}/node_modules`);71 if (isFile) {72 log("🖐 Bye Bye!", "yellow");73 }74 return;75 },76};7778//工具箱79async function tool(name, dir) {80 const answer = await inquirer.prompt([81 {82 type: "rawlist",83 message: "Action",84 name: "operation",85 choices: Object.keys(actions),86 },87 ]);88 const res = await actions[answer.operation]({ dir, name });89 if (!res) {90 return;91 }92 tool(name, dir);93}9495main();9697module.exports = { main, tool };
Utils
1const chalk = require("chalk");2const { spawn: _spawn } = require("child_process");34const spawn = async (...args) => {5 return new Promise((resolve) => {6 const proc = _spawn(...args);7 proc.stdout.pipe(process.stdout);8 proc.stderr.pipe(process.stderr);9 proc.on("close", (...restArgs) => {10 resolve(restArgs);11 });12 });13};1415const log = (msg, color = "green", ...arg) =>16 console.log(chalk[color](msg, arg));1718module.exports = { spawn, log };