新聞中心
使用 Node.js 構(gòu)建一個(gè)根據(jù)詢問(wèn)創(chuàng)建文件的命令行工具。
創(chuàng)新互聯(lián)是一家專(zhuān)業(yè)提供海鹽企業(yè)網(wǎng)站建設(shè),專(zhuān)注與成都網(wǎng)站制作、成都網(wǎng)站設(shè)計(jì)、外貿(mào)營(yíng)銷(xiāo)網(wǎng)站建設(shè)、成都h5網(wǎng)站建設(shè)、小程序制作等業(yè)務(wù)。10年已為海鹽眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專(zhuān)業(yè)的建站公司優(yōu)惠進(jìn)行中。
當(dāng)用于構(gòu)建命令行界面(CLI)時(shí),Node.js 十分有用。在這篇文章中,我將會(huì)教你如何使用 Node.js 來(lái)構(gòu)建一個(gè)問(wèn)一些問(wèn)題并基于回答創(chuàng)建一個(gè)文件的命令行工具。
開(kāi)始
首先,創(chuàng)建一個(gè)新的 npm 包(NPM 是 JavaScript 包管理器)。
mkdir my-scriptcd my-scriptnpm init
NPM 將會(huì)問(wèn)一些問(wèn)題。隨后,我們需要安裝一些包。
npm install --save chalk figlet inquirer shelljs
這是我們需要的包:
- Chalk:正確設(shè)定終端的字符樣式
- Figlet:使用普通字符制作大字母的程序(LCTT 譯注:使用標(biāo)準(zhǔn)字符,拼湊出圖片)
- Inquirer:通用交互式命令行用戶界面的集合
- ShellJS:Node.js 版本的可移植 Unix Shell 命令行工具
創(chuàng)建一個(gè) index.js 文件
現(xiàn)在我們要使用下述內(nèi)容創(chuàng)建一個(gè) index.js 文件。
#!/usr/bin/env nodeconst inquirer = require("inquirer");const chalk = require("chalk");const figlet = require("figlet");const shell = require("shelljs");
規(guī)劃命令行工具
在我們寫(xiě)命令行工具所需的任何代碼之前,做計(jì)劃總是很棒的。這個(gè)命令行工具只做一件事:創(chuàng)建一個(gè)文件。
它將會(huì)問(wèn)兩個(gè)問(wèn)題:文件名是什么以及文件后綴名是什么?然后創(chuàng)建文件,并展示一個(gè)包含了所創(chuàng)建文件路徑的成功信息。
// index.jsconst run = async () => {// show script introduction// ask questions// create the file// show success message};run();
***個(gè)函數(shù)只是該腳本的介紹。讓我們使用 chalk 和 figlet 來(lái)把它完成。
const init = () => {console.log(chalk.green(figlet.textSync("Node JS CLI", {font: "Ghost",horizontalLayout: "default",verticalLayout: "default"})));}const run = async () => {// show script introductioninit();// ask questions// create the file// show success message};run();
然后,我們來(lái)寫(xiě)一個(gè)函數(shù)來(lái)問(wèn)問(wèn)題。
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 introductioninit();// ask questionsconst answers = await askQuestions();const { FILENAME, EXTENSION } = answers;// create the file// show success message};
注意,常量 FILENAME 和 EXTENSIONS 來(lái)自 inquirer 包。
下一步將會(huì)創(chuàng)建文件。
const createFile = (filename, extension) => {const filePath = `${process.cwd()}/${filename}.${extension}`shell.touch(filePath);return filePath;};// ...const run = async () => {// show script introductioninit();// ask questionsconst answers = await askQuestions();const { FILENAME, EXTENSION } = answers;// create the fileconst 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 introductioninit();// ask questionsconst answers = await askQuestions();const { FILENAME, EXTENSION } = answers;// create the fileconst filePath = createFile(FILENAME, EXTENSION);// show success messagesuccess(filePath);};
來(lái)讓我們通過(guò)運(yùn)行 node index.js 來(lái)測(cè)試這個(gè)腳本,這是我們得到的:
完整代碼
下述代碼為完整代碼:
#!/usr/bin/env nodeconst 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 introductioninit();// ask questionsconst answers = await askQuestions();const { FILENAME, EXTENSION } = answers;// create the fileconst filePath = createFile(FILENAME, EXTENSION);// show success messagesuccess(filePath);};run();
使用這個(gè)腳本
想要在其它地方執(zhí)行這個(gè)腳本,在你的 package.json 文件中添加一個(gè) bin 部分,并執(zhí)行 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"}}
執(zhí)行 npm link 使得這個(gè)腳本可以在任何地方調(diào)用。
這就是是當(dāng)你運(yùn)行這個(gè)命令時(shí)的結(jié)果。
/usr/bin/creator -> /usr/lib/node_modules/creator/index.js/usr/lib/node_modules/creator -> /home/hugo/code/creator
這會(huì)連接 index.js 作為一個(gè)可執(zhí)行文件。這是完全可能的,因?yàn)檫@個(gè) CLI 腳本的***行是 #!/usr/bin/env node。
現(xiàn)在我們可以通過(guò)執(zhí)行如下命令來(lái)調(diào)用。
$ creator
總結(jié)
正如你所看到的,Node.js 使得構(gòu)建一個(gè)好的命令行工具變得非常簡(jiǎn)單。如果你希望了解更多內(nèi)容,查看下列包。
- meow:一個(gè)簡(jiǎn)單的命令行助手工具
- yargs:一個(gè)命令行參數(shù)解析工具
- pkg:將你的 Node.js 程序包裝在一個(gè)可執(zhí)行文件中。
在評(píng)論中留下你關(guān)于構(gòu)建命令行工具的經(jīng)驗(yàn)吧!
網(wǎng)頁(yè)題目:使用Node.js構(gòu)建交互式命令行工具
URL分享:http://www.5511xx.com/article/dppsoeh.html


咨詢
建站咨詢

