十分钟经过 NPM 建立一个命令行工具

大过年的,要不要写点代码压压惊?来花十分钟学一下怎么经过 NPM 构建一个命令行工具。node

写了一个小 demo,用于代替 touch 的建立文件命令 touchme ,能够建立自带“佛祖保佑”注释的文件。效果以下: git

命令能够带有一个参数,选择注释的符号github

如今,开始撸代码 ~web

首先建立一个文件夹,我起名字 create-file-cli 而后经过 npm init 命令建立 package.json 文件。npm

$ mkdir create-file-cli
$ cd create-file-cli
$ npm init -y

而后修改 package.json 添加一个 bin 字段,定义一个 touchme 命令,并指定该命令执行的文件。json

{
  "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数组

bin/touchme.js 以下工具

#!/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 定义命令选项并可定义参数。网站

经过 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 来查看帮助。

一个命令行工具就建立成功啦~~

相关文章
相关标签/搜索