当前位置: 首页 > 后端技术 > Node.js

Nodejs开发跨平台cli工具

时间:2023-04-03 22:33:12 Node.js

原文:https://blog.fengjx.com/pages...软件开发中有很多重复或者繁琐的工作,一些命令行工具可以简化我们的日常工作,提高效率。例如:搭建项目初始开发环境:create-react-app,vue-clihttp客户端:httpie,curlgit终端ui客户端gitui随着nodejs的发展,在各个领域都有完整的生态,使用nodejs开发commandlinetools直接阅读源码查看也是不错的选择:https://github.com/fengjx/kit...Howtorunanodejsscriptversion1//hello.jsconsole.log('helloworld')executenodehello.jsVersion2//hello.js#!/usr/bin/envnodeconsole.log('helloworld')executechmod755hello.js./hello.js工程开发运行一个nodejs脚本很很简单,它可以像一个shell脚本一样。但是要实现一个完整的功能,我们通常需要依赖第三方库。一个写得很好的工具需要一个发布平台供其他人使用。所以使用npm来管理项目是一个不错的选择。此外,一个易于使用的工具应该为用户提供文档,告诉用户可以传递哪些参数以及参数的含义是什么。如果我们重新开发它,那将是一件非常麻烦的事情。幸运的是,已经有第三方库封装了这部分功能。下面是一些封装好的类库。当然远不止于此。Commander命令行参数解析inquirer交互命令行参数解析shelljs跨平台shell命令pkg节点可执行文件打包工具更多第三方库可以查看:https://github.com/huaize2020...这里做一个简单的demo,更多用法参考官方文档bin/hello.js#!/usr/bin/envnodeconst{Command}=require('commander')constinquirer=require('inquirer')constprogram=newCommand()program.version('0.0.1')console.log('hellonodecli')//https://github.com/tj/commander.js//解析命令行参数//hello-d-nfengjxprogram.option('-d,--debug','debug')program.option('-n,--name','你的名字')program.parse(process.argv)constopts=program.opts()if(opts.debug){console.log('opts:',opts)}console.log(`hello:${opts.name}`)//https://github.com/SBoudrias/Inquirer.js/tree/master/packages/inquirer/examples//交互终端constquestions=[{type:'input',name:'username',message:"Enteraccountnumber",},{type:'password',name:'password',message:"Enterpassword"}]inquirer.prompt(questions).then((answers)=>{console.log(JSON.stringify(answers,null,''))})execute$nodebin/hello.js-d-nfengjxhellonodecliopts:{debug:true,name:'fengjx'}hello:fengjx?输入帐户fjx?Enterpassword[hidden]{"username":"fjx","password":"1024"}基本框架设计对于一个命令行工具,通常包括以下步骤:定义参数参数验证&解析读取参数,并执行相关逻辑我们可以封装一个统一的接口,不同的工具实现相应的方法,所有相同的逻辑都可以放在入口函数中。每个命令只需要实现对应接口Cmd定义的方法接口cmd.js/***命令接口*/classCmd{/***命令名**@returnsstring*/actionName(){}/***命令参数配置*@returnsOption[]*/makeOptions(){}/***业务逻辑*@param{*}opts参数解析结果*///eslint-disable-next-lineno-unused-varsexec(opts){}}module.exports=Cmd完整项目代码:https://github.com/fengjx/kit打包安装功能开发完成后,需要发布出来供其他人使用。如果有node环境,可以直接使用源码安装,也可以直接打包成可执行文件,这样别人使用的时候就不需要安装node了。通过npm全局安装gitclonehttps://github.com/fengjx/kit.gitcdkit#安装依赖npmi#全局安装npmi-g.#测试是否安装成功kit--help执行需要打包后的可执行文件的nodejs依赖于v8引擎,所以需要有node环境才能运行。pkg工具可以将node环境和代码打包在一起(所以打包后会大50M左右),得到一个可执行文件,上传到cdn供其他人直接下载使用。打包命令“pkg:mac”定义在package.js:"pkg.--targetsnode14-macos-x64--output./.dist/kit-macos-64","pkg:win":"pkg.--targetsnode14-win-x64--output./.dist/kit-win-64","pkg:linux":"pkg.--targetsnode14-linux-x64--output./.dist/kit-linux-64”,不同的平台需要指定不同的参数,更多的参数可以参考官方文档:https://github.com/vercel/pkgpackage不同平台下的package包通过npmnpmrunpkg:mac#pkg:win或者pkg:linuxtest$cd.dist$./kit-macos-64hello--version1.0.0$./kit-macos-64--help用法:kit[选项][命令]选项:-V,--version输出版本号-h,--help显示命令帮助命令:hello[options]gl-bcl[options]help[command]显示命令帮助