1. 程式人生 > >使用 Node.js 構建互動式命令列工具

使用 Node.js 構建互動式命令列工具

使用 Node.js 構建一個根據詢問建立檔案的命令列工具。

當用於構建命令列介面(CLI)時,Node.js 十分有用。在這篇文章中,我將會教你如何使用 Node.js 來構建一個問一些問題並基於回答建立一個檔案的命令列工具。

開始

首先,建立一個新的 npm 包(NPM 是 JavaScript 包管理器)。

  1. mkdirmy-script
  2. cdmy-script
  3. npm init

NPM 將會問一些問題。隨後,我們需要安裝一些包。

  1. npm install --save chalk figlet inquirer shelljs

這是我們需要的包:

  • Chalk:正確設定終端的字元樣式
  • Figlet:使用普通字元製作大字母的程式(LCTT 譯註:使用標準字元,拼湊出圖片)
  • Inquirer:通用互動式命令列使用者介面的集合
  • ShellJS:Node.js 版本的可移植 Unix Shell 命令列工具

建立一個 index.js 檔案

現在我們要使用下述內容建立一個 index.js 檔案。

  1. #!/usr/bin/env node
  2. const inquirer =require("inquirer");
  3. const chalk =require("chalk");
  4. const figlet =require("figlet");
  5. const shell =require("shelljs");

規劃命令列工具

在我們寫命令列工具所需的任何程式碼之前,做計劃總是很棒的。這個命令列工具只做一件事:建立一個檔案

它將會問兩個問題:檔名是什麼以及檔案字尾名是什麼?然後建立檔案,並展示一個包含了所建立檔案路徑的成功資訊。

  1. // index.js
  2. const run = async ()=>{
  3. // show script introduction
  4. // ask questions
  5. // create the file
  6. // show success message
  7. };
  8. run();

第一個函式只是該指令碼的介紹。讓我們使用 chalkfiglet

來把它完成。

  1. constinit=()=>{
  2. console.log(
  3. chalk.green(
  4. figlet.textSync("Node JS CLI",{
  5. font:"Ghost",
  6. horizontalLayout:"default",
  7. verticalLayout:"default"
  8. })
  9. )
  10. );
  11. }
  12. const run = async ()=>{
  13. // show script introduction
  14. init();
  15. // ask questions
  16. // create the file
  17. // show success message
  18. };
  19. run();

然後,我們來寫一個函式來問問題。

  1. const askQuestions =()=>{
  2. const questions =[
  3. {
  4. name:"FILENAME",
  5. type:"input",
  6. message:"What is the name of the file without extension?"
  7. },
  8. {
  9. type:"list",
  10. name:"EXTENSION",
  11. message:"What is the file extension?",
  12. choices:[".rb",".js",".php",".css"],
  13. filter:function(val){
  14. return val.split(".")[1];
  15. }
  16. }
  17. ];
  18. return inquirer.prompt(questions);
  19. };
  20. // ...
  21. const run = async ()=>{
  22. // show script introduction
  23. init();
  24. // ask questions
  25. const answers = await askQuestions();
  26. const{ FILENAME, EXTENSION }= answers;
  27. // create the file
  28. // show success message
  29. };

注意,常量 FILENAMEEXTENSIONS 來自 inquirer 包。

下一步將會建立檔案。

  1. const createFile =(filename, extension)=>{
  2. const filePath =`${process.cwd()}/${filename}.${extension}`
  3. shell.touch(filePath);
  4. return filePath;
  5. };
  6. // ...
  7. const run = async ()=>{
  8. // show script introduction
  9. init();
  10. // ask questions
  11. const answers = await askQuestions();
  12. const{ FILENAME, EXTENSION }= answers;
  13. // create the file
  14. const filePath = createFile(FILENAME, EXTENSION);
  15. // show success message
  16. };

最後,重要的是,我們將展示成功資訊以及檔案路徑。

  1. const success =(filepath)=>{
  2. console.log(
  3. chalk.white.bgGreen.bold(`Done! File created at ${filepath}`)
  4. );
  5. };
  6. // ...
  7. const run = async ()=>{
  8. // show script introduction
  9. init();
  10. // ask questions
  11. const answers = await askQuestions();
  12. const{ FILENAME, EXTENSION }= answers;
  13. // create the file
  14. const filePath = createFile(FILENAME, EXTENSION);
  15. // show success message
  16. success(filePath);
  17. };

來讓我們通過執行 node index.js 來測試這個指令碼,這是我們得到的:

完整程式碼

下述程式碼為完整程式碼:

  1. #!/usr/bin/env node
  2. const inquirer =require("inquirer");
  3. const chalk =require("chalk");
  4. const figlet =require("figlet");
  5. const shell =require("shelljs");
  6. constinit=()=>{
  7. console.log(
  8. chalk.green(
  9. figlet.textSync("Node JS CLI",{
  10. font:"Ghost",
  11. horizontalLayout:"default",
  12. verticalLayout:"default"
  13. })
  14. )
  15. );
  16. };
  17. const askQuestions =()=>{
  18. const questions =[
  19. {
  20. name:"FILENAME",
  21. type:"input",
  22. message:"What is the name of the file without extension?"
  23. },
  24. {
  25. type:"list",
  26. name:"EXTENSION",
  27. message:"What is the file extension?",
  28. choices:[".rb",".js",".php",".css"],
  29. filter:function(val){
  30. return val.split(".")[1];
  31. }
  32. }
  33. ];
  34. return inquirer.prompt(questions);
  35. };
  36. const createFile =(filename, extension)=>{
  37. const filePath =`${process.cwd()}/${filename}.${extension}`
  38. shell.touch(filePath);
  39. return filePath;
  40. };
  41. const success = filepath =>{
  42. console.log(
  43. chalk.white.bgGreen.bold(`Done! File created at ${filepath}`)
  44. );
  45. };
  46. const run = async ()=>{
  47. // show script introduction
  48. init();
  49. // ask questions
  50. const answers = await askQuestions();
  51. const{ FILENAME, EXTENSION }= answers;
  52. // create the file
  53. const filePath = createFile(FILENAME, EXTENSION);
  54. // show success message
  55. success(filePath);
  56. };
  57. run();

使用這個指令碼

想要在其它地方執行這個指令碼,在你的 package.json 檔案中新增一個 bin 部分,並執行 npm link

  1. {
  2. "name":"creator",
  3. "version":"1.0.0",
  4. "description":"",
  5. "main":"index.js",
  6. "scripts":{
  7. "test":"echo \"Error: no test specified\" && exit 1",
  8. "start":"node index.js"
  9. },
  10. "author":"",
  11. "license":"ISC",
  12. "dependencies":{
  13. "chalk":"^2.4.1",
  14. "figlet":"^1.2.0",
  15. "inquirer":"^6.0.0",
  16. "shelljs":"^0.8.2"
  17. },
  18. "bin":{
  19. "creator":"./index.js"
  20. }
  21. }

執行 npm link 使得這個指令碼可以在任何地方呼叫。

這就是是當你執行這個命令時的結果。

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

這會連線 index.js 作為一個可執行檔案。這是完全可能的,因為這個 CLI 指令碼的第一行是 #!/usr/bin/env node

現在我們可以通過執行如下命令來呼叫。

  1. $ creator

總結

正如你所看到的,Node.js 使得構建一個好的命令列工具變得非常簡單。如果你希望瞭解更多內容,檢視下列包。

  • meow:一個簡單的命令列助手工具
  • yargs:一個命令列引數解析工具
  • pkg:將你的 Node.js 程式包裝在一個可執行檔案中。

在評論中留下你關於構建命令列工具的經驗吧!


via: https://opensource.com/article/18/7/node-js-interactive-cli

作者:Hugo Dias 選題:lujun9972 譯者:bestony 校對:wxy

本文由 LCTT 原創編譯,Linux中國 榮譽推出