3 回答

TA貢獻(xiàn)2037條經(jīng)驗(yàn) 獲得超6個(gè)贊
創(chuàng)建項(xiàng)目:
新建一個(gè)文件夾,假設(shè)我們?nèi)∶麨閠bjnode
cd tbjnode
然后初始化項(xiàng)目
npm init
現(xiàn)在,我們需要修改 package.json 文件
1:刪除main入口
2:添加preferGlobal設(shè)為true:該選項(xiàng)會(huì)提示用戶全局安裝
3:添加bin對(duì)象,用于建立索引:比如執(zhí)行tbjname相當(dāng)于執(zhí)行index.js
修改后的package.json如下:
{
"name": "tbjnode",
"version": "1.0.3",
"description": "tbj node project cli",
"preferGlobal": true,
"keywords": [
"file",
"search"
],
"bin": {
"filesearch": "index.js"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "zhishui",
"license": "ISC"
}
bin下的filesearch用來(lái)指定filesearch命令執(zhí)行的文件為index.js
使用 npm link ,綁定全局,不用重新安裝。
好了,現(xiàn)在我們開(kāi)始寫(xiě)一個(gè)功能,用來(lái)查詢某個(gè)文件夾下是否有指定的文件。
我們新建一個(gè) index.js
編寫(xiě)如下代碼:
#!/usr/bin/env node
var exec = require('child_process').exec;
// 獲取用戶輸入內(nèi)容
var userArgv = process.argv.slice(2);
var searchPath = userArgv[0];
var searchFile = userArgv[1];
var commond = "find ";
// 判斷用戶輸入是否錯(cuò)誤
if(userArgv.length !=2) {
console.log("input commond link this 'filesearch filepath filename'");
} else {
commond += searchPath + ' -iname '+ searchFile;
var child = exec(commond, function(err, stdout, stderr) {
if(err) {
throw err;
}
console.log(stdout);
});
}
ok?,F(xiàn)在開(kāi)始測(cè)試一下: filesearch ./ package.json 。就可以看到結(jié)果了。
但是現(xiàn)在TJ大神也做了一個(gè)特別酷的工具。 commander
API地址: commander API
舉例一個(gè)example:
新建一個(gè)文件 testCommander.js
然后在bin里,添加一個(gè)索引。
bin: {
"filesearch": "index.js",
"testC": "testCommander.js"
}
在 testCommander.js 寫(xiě)入以下代碼:
#!/usr/bin/env node
var program = require('commander');
program
.version('0.0.1')
.option('-C, --chdir <path>', 'change the working directory')
.option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
.option('-T, --no-tests', 'ignore test hook')
program
.command('setup')
.description('run remote setup commands')
.action(function() {
console.log("setup");
});
program.parse(process.argv);
執(zhí)行 testC -h ,就可以看到命令行結(jié)果。
commander這里主要用了五個(gè)接口:
1. version: 設(shè)定版本號(hào)
2. option: 對(duì)該命令介紹以及一些參數(shù)的執(zhí)行
3. command: 新增一個(gè)子命令,執(zhí)行``testC setup``
4. description: 對(duì)該命令的描述
5. action: 該子命令的要執(zhí)行的操作。
其他的操作請(qǐng)查看該文檔接口。
- 3 回答
- 0 關(guān)注
- 1005 瀏覽
添加回答
舉報(bào)