手机版
你好,游客 登录 注册
背景:
阅读新闻

使用 Node.js 构建交互式命令行工具

[日期:2019-01-06] 来源:Linux中国  作者:Linux [字体: ]

使用 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中国 荣誉推出

Linux公社的RSS地址:https://www.linuxidc.com/rssFeed.aspx

本文永久更新链接地址https://www.linuxidc.com/Linux/2019-01/156210.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款