Nodejs学习记录: 制做命令行工具

咱们常常会遇到这样的需求:想要将Node模块转变成一个Linux命令行工具,包括支持命令行选项/参数。html

小实例

开始编写以前须要确认的一件事情是你已经安装了Node.js。你能够在命令行中运行 which node 来确认是否已经安装,或者运行 node -v 查看 node 的版本 。若是你已经安装了node,你能够看到相似于下面的输出结果,通常状况安装了node.js 顺带npm工具自动安装了。前端

$ which node
/d/Program Files/nodejs/node
$ node -v
v7.9.0

建立目录

代码 :https://github.com/JXtreehous...node

首先任意建立一个文件夹,初始化 package.json 文件,在该文件夹下建立bin目录:linux

$ mkdir command-line-tool #建立一个文件夹
$ cd command-line-tool && mkdir bin
$ npm init #初始化 `package.json` 文件

编写命令行

cd到 bin 目录下,新建一个 commander.js 文件(名字自取),编写以下代码,在js文件顶部加上 #!/usr/bin/env node 这段代码:git

上面的 #!/usr/bin/env node (或者/d/Program Files/nodejs/node
),表示用后面的路径所示的程序来执行当前文件夹。还须要一个 package.json 文件github

{
  "name": "command-line-tool",
  "version": "0.1.0",
  "description": "a commander example",
  "main": "commander.js",
  "bin": {"commander": "bin/commander.js"},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "AlexZ33",
  "license": "MIT"
}

运行 node bin/wcommander.js 会显示当前文件夹下的因此文件和文件夹名web

package.json 文件中 bin 里面的内容表示这个字段将commander 命令映射到了你的 bin/commander.js 脚本npm

npm-link
package.json#bin
版本号管理:此工具采用 npm版本号采用的 semver 规则json

npm link

确保你在 package.json 文件中添加了 bin 节点。而后打开命令了工具进入command-line-tool目录segmentfault

"bin": {"commander": "bin/commander.js"}

启用命令行:

打开命令行,输入npm link会自动添加全局的symbolic link,而后就可使用本身的命令了。

npm link

这里咱们经过npm link在本地安装了这个包用于测试,而后就能够经过

$ commander
//bin
//package.json

$ commander -v
//version is 1.0.0

$ commander -h 
//Useage:
//  -v --version [show version]

更多npm link的信息请查看 npm官方文档

用Phantom和Commandder制做一个截屏工具

如上面的小例子,第一行咱们依然

#!/usr/bin/env node

而后要提供命令行参数/选项,包括重要的--help,须要使用Commander模块:

const phantom = require('phantom')
const program = require('commander');

program
  .version('0.0.1')
  .option('-s, --source[website]', 'Source website')
  .option('-f, --file[filename]', 'filename')
  .parse(process.argv)

const run = async() => {
  
  const instance = await phantom.create();
  const page = await instance.createPage();
  await page.on('onResourceRequested', function(requestData) {
    console.info('Requesting', requestData.url)
  });
  const status = await page.open(program.source)
  
  await instance.exit();
}
run()

上面这段

const run = async() => {
  
}
run()

能够直接写成自执行匿名函数

(async function(){
  
})();

图片描述
npm phantom

处理命令行参数的经常使用模块

yargs 和 minimist 都是用来解析命令行参数的,可是有一点须要注意的是 yargs 内部的解析引擎就是 minimist。minimist 就是一个轻量级的命令行参数解析引擎。

  • inquirer: 一个用户与命令行交互的工具

它们二者共同点确定有,不一样点就是 yargs 是对 minimist 进行了更进一步的封装。

有意思的包

node-getmac

/**
 * @file get local mac address
 * @author liulangyu(liulangyu90316@gmail.com)
 */

var execSync = require('child_process').execSync;
var platform = process.platform;

module.exports = (function () {
    var cmd = {
        win32: 'getmac',
        darwin: 'ifconfig -a',
        linux: 'ifconfig -a || ip link'
    }[platform];

    var regStr = '((?:[a-z0-9]{2}[:-]){5}[a-z0-9]{2})';

    var macReg = new RegExp('ether\\s' + regStr + '\\s', 'i');

    try {
        var data = execSync(cmd).toString();
        var res = {
            win32: new RegExp(regStr, 'i').exec(data),
            darwin: macReg.exec(data),
            linux: macReg.exec(data)
        }[platform];


        if (res) {
            return res[1];
        }
    }
    catch (e) {
        return '';
    }
})();

参考

使用Node.js建立命令行工具
Building a simple command line tool with npm
Nodejs 制做命令行工具
Node.js 命令行程序开发教程 by 阮一峰
前端扫盲-之打造一个Node命令行工具

相关文章
相关标签/搜索