使用Node.js构建命令行工具

使用Node.js和npm构建脚本或命令行工具。

一、包装shell命令

第一步:创建一个npm项目

npm init;
 
 
  • 1

第二步:创建一个js文件(index.js),包含要运行的脚本

!/usr/bin/env node
console.log('Hello, world!');
 
 
  • 1
  • 2

需要注意的是,需要添加片段标识符!/usr/bin/env node”,告知脚本使用Node执行。 
第三步:在package.json文件中补充bin部分

{
    ...
    "author": "ligang",
    "bin": {
        "hi": "./index.js"
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

本示例中,使用“hi”作为外部调用的命令。 
第四步:安装相关脚本,并运行测试

$ sudo npm install -g
$ hi
Hello, world!
 
 
  • 1
  • 2
  • 3

其他:查看安装情况

# 查看链接的位置
$ which hi
/usr/local/bin/hi
# 查看文件实际位置
$ readlink /usr/local/bin/hi
../lib/node_modules/commander_test/test/index.js
# 进入项目目录,查看链接情况
$ sudo npm link
/usr/local/bin/hi -> /usr/local/lib/node_modules/commander_test/test/index.js
/usr/local/lib/node_modules/commander_test -> /Users/ligang/myworkspace/commander_test
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

二、解析命令行选项

有时需要根据用户输入进行交互,最常用的方式是传递给命令行一些有价值的参数。 
可以通过“process.argv”将参数传递给Node脚本,可以使用commander;大多数依赖回调或promise等待用户输入,我们可以使用co-prompt利用ES6的yield关键字。 
第一步:安装commander、co-prompt

$ npm install --save commander
$ npm install --save co-prompt
 
 
  • 1
  • 2

第二步:定义选项

#!/usr/bin/env node --harmony
var co = require('co');
var prompt = require('co-prompt');
var program = require('commander');
program
    .version('0.0.2')
    .arguments('<file>')
    .option('-u, --username <username>', 'The user to authenticate as')
    .option('-p, --paswword <password>', 'The user\'s password')
    .action(function(file){
        co(function *(){
            var username = yield prompt('username: ');
            var password = yield prompt.password('password: ');
            console.log('user: %s pass: %s file: %s',
                username, password, file);
        });
    })
    .parse(process.argv);
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

第三步:测试

$ sudo npm install -g
$ hi nb.js
 
 
  • 1
  • 2

hi

# 查看帮助
$ hi --help
 
 
  • 1
  • 2

hi-help 
注意yield是ES6命令,所以需要Node 4.0.0+。但是可以通过添加--harmony标记来兼容0.11.2。

三、实现npm init

通过npm init命令可以初始化package.json

$ npm init
 
 
  • 1

npm-init
通过Node实现:

#!/usr/bin/env node --harmony

var co = require('co');
var prompt = require('co-prompt');
var program = require('commander');

var fs = require('fs');
var jsonfile = require('jsonfile');

var defaultConf = {
    name: process.env.PWD.split("/").pop(),
    version: "1.0.0",
    description: "",
    main: "index.js",
    directories: {
        "test": "test"
    },
    dependencies: {},
    devDependencies: {},
    scripts: {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    author: "",
    license: "ISC"
};

program
    .command('init')
    .description('run the given remote command')
    .action(function () {
        co(function*() {
            var params = {};
            params.name = yield prompt('name: (' +  process.env.PWD.split("/").pop() +')');
            params.version = yield prompt('version: (1.0.0)');
            params.description = yield prompt('description: ');
            params.repository = yield prompt('git repository: ');
            params.keywords = yield prompt('keywords: ');
            params.author = yield prompt('author: ');
            params.license = yield prompt('license: (ISC)');

            // 生成模板
            var result = fileTemplate(params);
            console.info(result);

            // 是否同意
            var agree = yield prompt('Is this ok? (yes)');
            if(agree != "no"){
                jsonfile.writeFileSync("package_test.json", result, {spaces: 2});
            }
            process.exit(0);
        });
    });
program.parse(process.argv);


function fileTemplate(params) {
    return Object.assign(defaultConf, params);
}
 
 
  • 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
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58

测试:

$ lg init
name: (commander_test)lg_test
version: (1.0.0)1.0.0
description: 模拟npm init
git repository:
keywords: npm init commander
author: ligang
license: (ISC)
{ name: 'lg_test',
  version: '1.0.0',
  description: '模拟npm init',
  main: 'index.js',
  directories: { test: 'test' },
  dependencies: {},
  devDependencies: {},
  scripts: { test: 'echo "Error: no test specified" && exit 1' },
  author: 'ligang',
  license: '',
  repository: '',
  keywords: 'npm init commander' }
Is this ok? (yes)yes
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

package_test.json

参考地址:https://developer.atlassian.com/blog/2015/11/scripting-with-node/#packaging-shell-commands

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值