為什么使用nodejs實現命令行工具
Node.js是一個基於事件驅動I/O的JavaScript環境,基於Google的V8引擎,V8引擎執行Javascript的速度非常快,性能非常好。
眾所周知,javascript已經成為最流行的編程語言,以前javascript只是用來實現web前端功能,但是nodejs的出現使得javascript不僅可以服務於web的后端,還能夠作為通用的腳本語言,類似python/perl一樣,實現更多的桌面相關的任務。
nodejs除了於web框架一起實現web后端的功能,作為devops我們可以使用nodejs做很多其他的事情:
- 遍歷目錄,讀寫json和yaml配置文件;
- 異步執行,或者多進程調用外部系統命令;
- http請求,解析,或者生成web;
- 查詢數據庫mango,redis,其他數據庫;
- 解析日志,監聽問題,發送郵件;
安裝nodejs
wget https://nodejs.org/dist/v12.18.0/node-v12.18.0-linux-x64.tar.xz
tar -xvf node-v12.18.0-linux-x64.tar.xz
mv node-v12.18.0-linux-x64 nodejs
ln -s /app/software/nodejs/bin/npm /usr/local/bin/
ln -s /app/software/nodejs/bin/node /usr/local/bin/
國內用戶使用淘寶鏡像:
npm install -g cnpm --registry=https://registry.npm.taobao.org
然后使用cnpm來安裝其他的模塊
實現第一個helloworld的命令
#!/usr/bin/env node
console.log('hello world');
增加權限
chmod u+x yourscript
運行./yourscript
hello world
簡單的腳本參數解析
process.argv中包含了所有的參數
腳本中增加輸入來查看參數:console.log(process.argv)
執行腳本:./yourscript -g -f
輸出為:[ 'node', '/home/george/yourscript', '-f', '-g' ]
程序的退出
if (err) {
process.exit(1);
} else {
process.exit(0);
}
將命令行工具打包為可安裝的npm包
生成package.json:npm init
修改package.json:
"name": "helloworld”,
"author": "cicdops",
"license": "Apache-2.0",
+ "bin": {
+ "helloworld": "./index.js"
+ }
本地安裝:
npm install -g
$ helloworld
Hello, world!
其他人可以通過命令安裝:npm install -g helloworld
參考:
https://blog.developer.atlassian.com/scripting-with-node/
https://shapeshed.com/command-line-utilities-with-nodejs/
