自定义命令行工具基于Nodejs
每个人都会做一些简单的小工具去方便自己平时的工作,比如批处理文件。写个有界面的工具吧,有点费劲和没必要;如果能在命令行里面敲几个简单命令就能完成,就方便很多了,而我们又是前端开发,基于nodejs,学习的门槛就更低了
一、前期准备
需要下载两个node的插件
- liftoff (执行命令行插件)
- minimist (读取命令行参数插件)
二、文件夹结构
需要将文件内容保存在指定文件夹才有效:windows用户一般为在C:\Users\用户名\AppData\Roaming\npm
1 2 3 4 5 6 7 8 | npm |--hello.cwd //windows下的命令入口文件(自定义的命令) |--node_modules //nodejs的全局插件保存目录 | |--hello //hello命令插件的目录 | | |--hello.js //hello命令的代码实现文件 | | |--node_modules //命令行工具依赖的两个插件包 | | | |--liftoff | | | |--minimist |
hello.cwd文件
1 2 3 4 5 | @IF EXIST "%~dp0\node.exe" ( "%~dp0\node.exe" "%~dp0\node_modules\hello\hello.js" %* ) ELSE ( node "%~dp0\node_modules\hello\hello.js" %* ) |
假设我们的命令行名字叫:hello,可以看出其实最终是用node命令执行我们的hello.js
hello.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | //加载引用命令工具的第三方插件包 var Liftoff = require( 'liftoff' ); var argv = require( 'minimist' )(process.argv.slice(2)); //实例化一个命令行工具 var cli = new Liftoff({ name: 'hello' , // 命令名字 processTitle: 'hello' , //同上即可 moduleName: 'hello' , //同上即可 configName: 'hello-conf' , //配置文件名称 // 设置为支持js后缀 extensions: { '.js' : null } }); //启动命令 cli.launch({ cwd: argv.r || argv.root, //当前输入hello命令的目录 configPath: argv.f || argv.file //读取当前命令目录下的配置文件路径 }, function (env) { //捕获命令行 var command = argv[ "_" ]; console.log(env.cwd); console.log(env.configPath); }); |
就这样一个简单的工具就完成了,就可以在CMD
命令任意地方输入:hello
三、测试实验
假设我们在D盘下,而且我们D盘存在hello-conf.js
配置文件,执行命令
1 | d:\> hello check --yousay haha |
此时如何获得以上命令中的参数?
1 2 3 4 5 | //在启动命令的回调中,可以这样获取 env.cwd //输出:D:\ env.configPath //输出:D:\hello-conf.js argv["_"][0] //输出:check argv.yousay //输出:haha |
有这些参数后,就可以定义很多不同的hello
命令处理了,比如读取当前文件夹下所有图片,然后进行压缩,再生出新的图片等等
PS:小组的feg命令也就是这样诞生的了
手机阅读请扫描下方二维码:
前辈您好,晚辈有事请教可否回邮
1
555
1
1
1
1
1
1
1
1
1
1
1
1
1
1
12345678

555
555
555
xdhgygszcnzqdyuekhgv
12345678

12345678

1
12345678

12345678

12345678
'and/**/extractvalue(1,concat(char(126),md5(1224859183)))and'
12345678
"and/**/extractvalue(1,concat(char(126),md5(1618104583)))and"
extractvalue(1,concat(char(126),md5(1856374166)))
12345678
'and(select'1'from//cast(md5(1041258679)as//int))>'0
1

1

1

1

1

1

1

1
1
1
555
1
1
1
555
1
1

1

1
555
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1