寫了一個小 demo,用於代替 touch
的建立文件命令 touchme
,能夠建立自帶「佛祖保佑」註釋的文件。效果以下: javascript
命令能夠帶有一個參數,選擇註釋的符號java
如今,開始擼代碼 ~node
首先建立一個文件夾,我起名字 create-file-cli
而後經過 npm init
命令建立 package.json
文件。git
$ mkdir create-file-cli
$ cd create-file-cli
$ npm init -y複製代碼
而後修改 package.json
添加一個 bin
字段,定義一個 touchme
命令,並指定該命令執行的文件。github
{
"name": "create-file-cli",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"bin": {
"touchme": "bin/touchme.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}複製代碼
接下來實現 bin/touchme.js
,要用到 Commander.js -- node.js 命令行接口的完整解決方案。看不懂英文文檔還有貼心的中文 README。npm
bin/touchme.js
以下json
#!/usr/bin/env node
const program = require('commander');
const gen = require('../lib/generate-file');
program
// 版本信息
.version('0.0.4', '-v, --version')
// 用法說明
.usage('<file ...> [options]')
// 選擇名 選項描述 默認值
// 選項 能夠帶有一個參數 能夠經過 program.copy 獲取該選項信息
// 若是沒有參數 該值爲 true
.option('-c, --copy <source>', 'copy file and add comment')
.option('-H, --hashtag', `comment by '#'`)
.option('-s, --slash', `comment by '/'`)
.parse(process.argv);
function resolve(program) {
// 沒有匹配任何選項的參數會被放到數組 args 中
const { copy, hashtag, slash, args } = program;
if (!args.length) {
console.log('Please input filename.');
return;
}
if (copy === true) {
console.log('You should copy at least one file.');
return;
}
let type = 'star';
if (slash) type = 'slash';
if (hashtag) type = 'hashtag';
for (let i = 0; i < args.length; i++) {
gen(args[i], copy, type);
}
}
resolve(program);
複製代碼
具體 lib/generate-file.js 實現見 https://github.com/G-lory/create-file-cli/ 就是簡單的建立一個文件並寫入註釋。數組
經過 option 定義命令選項並可定義參數。bash
經過 program 能夠獲取命令行輸入的參數信息。工具
如今功能寫完了,剩下的事情就是發佈了。首先要到 https://www.npmjs.com 查找一下本身的包名有沒有人已經發布了,若是有的話,你須要先修改包名。而後在 https://www.npmjs.com 註冊一個帳號。記住本身的帳號密碼和郵箱後,回到命令行。
$ npm login
Username: ...
Password:
Email: (this IS public)
Logged in as ... on https://registry.npmjs.org/.複製代碼
注意登陸成功後顯示的是 https://registry.npmjs.org/ 不少同窗設置了淘寶的鏡像,顯示的就不是這個地址,那麼要記得改回來。
$ npm config set registry=http://registry.npmjs.org
複製代碼
而後就能夠發佈包了。
$ npm publish複製代碼
若是以後有修改,更改一下 package.json
中的版本號 而後再次執行 npm publish
便可。
發佈後能夠去 npm 網站搜索一下本身的包。而後就是安裝測試一下功能。
全局安裝一下
npm install create-file-cli -g
複製代碼
而後就可使用 touchme
命令建立文件了。也可使用 touchme -h
來查看幫助。
一個命令行工具就建立成功啦。
第一次在掘金寫文章,仍是有點(劃掉)很是水,嗯,新的一年會加油的。