Nodejs 除了编写服务器端程序还可以编写命令行工具,如 gulp.js 就是 Nodejs 编写的。
接下来我们来实现一个添加时间戳的命令:$ timestamp action
https://www.npmjs.com/package/timestamp007
1. 需要用的模块:
commander 模块
fs 模块
2. 命令格式
编写命令行工具前,首先定义命令的使用方式:
如:
- 给某个页面添加时间戳 $ timestamp action /project/index.html
- 在非项目录下运行 需要制定项目目录 $ timestamp action /Users/river/web
3. 常见的命令格式
command [options] [arguments]
含义如下:
在查看命令帮助时会出现 [],<>,| 等符号,他们的含义分别是
如 timestamp 命令的使用方法描述如下:
Usage: timestamp [options] [command]
-------------------------------------------------------------
接下来,我们一步步来创建我们的命令行项目:
1. 首先 创建一个空的项目文件夹,然后再通过 npm init 来初始化 package.json 文件夹:
$ mkdir timestamp
$ cd timestamp
$ npm init
2. 初始化完毕后
安装 commander 模块:
$ npm install commander --save;
安装 fs 模块:
$ npm install fs --save
3. 安装完毕后
新建文件 bin/timestamp;
文件代码如下:
- # ! /usr/bin / env node
- var progarm = require('commander');
- //命令版本号
- progarm.version('0.0.1');
- //help命令
- progarm.command('help').description('显示使用帮助').action(function() {
- progarm.outputHelp();
- });
- progarm.command('action [dir]').description('加时间戳').action(require('../lib/readfile')).action(function(dir) {
- console.log("极客出品")
- });
- //开始解析命令
- progarm.parse(process.argv)
文件的第一行:
- # ! /usr/bin / env node:指定当前文件使用哪个解释器来执行。
- progarm.command('help').description('显示使用帮助').action(function() {
- progarm.outputHelp();
- });
4. 编写 readfile.js
在 timestamp 目录下
$ mkdir lib
cd lib
新建 readfile.js, 文件内容如下:
- var fs = require('fs'); //调用fs模块
- module.exports = function(dir) { //传入的目录,如果没有参数,则默认为当前目录
- dir = dir || '.';
- if (dir.indexOf(".html") > 0) {
- addtimestimp(dir); //如果参数是.html文件
- } else {
- fs.readdir(dir,
- function(err, files) { //如果不是html文件则遍历文件夹下所有的.html文件
- if (err) {
- console.log(err)
- } else {
- files.forEach(function(index) {
- var path = dir + "/" + index;
- if (index.indexOf('.html') > 0) {
- addtimestimp(path);
- }
- })
- }
- })
- }
- };
- function addtimestimp(path) {
- fs.readFile(path, 'utf-8',
- function(err, data) { //读取文件内容
- if (err) {
- console.log(err)
- } else {
- var nowtime = Date();
- var timestamp = Date.parse(nowtime); //以当前时间创建时间戳
- var newCSS = ".css?t=" + timestamp;
- var testcss = /[.]{1}css(\?t=[0-9]{0,})?/g;
- var newjs = ".js?t=" + timestamp;
- var testjs = /[.]{1}js(\?t=[0-9]{0,})?/g;
- var newpng = ".png?t=" + timestamp;
- var testpng = /[.]{1}png(\?t=[0-9]{0,})?/g;
- var newjpg = ".jpg?t=" + timestamp;
- var testjpg = /[.]{1}jpg(\?t=[0-9]{0,})?/g;
- var newdata = (((data.replace(testcss, newcss)).replace(testjs, newjs)).replace(testpng, newpng)).replace(testjpg, newjpg);
- fs.writeFile(path, newdata,
- function(err) { //增加时间戳后写入
- if (err) {
- console.log(err);
- } else {
- console.log(path + "加时间戳完成")
- }
- });
- }
- })
- }
5. 编辑 package.json
- {
- "name": "timestamp007",
- "version": "0.0.6",
- "description": "add a timestamp to the html files",
- "main": "index.js",
- "scripts": {
- "test": "echo \"Error: no test specified\" && exit 1"
- },
- "author": "river.cao",
- "license": "ISC",
- "bin": {
- "timestamp": "./bin/timestamp"
- },
- "repository": {
- "type": "git",
- "url": "https://github.com/caojiangtao/timestamp"
- },
- "dependencies": {
- "commander": "^2.9.0",
- "fs": "0.0.2"
- }
- }
可以看到 package.json 增加了 bin 属性,那么 bin 属性的作用是什么呢?
bin 属性用来指定当前模块需要连接的命令,在这里我们指定了 timestamp 命令是执行文件 :
./bin/timestamp
重点来了为了让这个设置生效,还需要执行以下命令来进行连接
$ sudo npm link
那么执行完毕了,我就可以验证命令行是否生效了,
接下来执行:
$ timestamp help
如果看到如下内容:
- Usage: timestamp[options][command] Commands: help显示使用帮助action[dir]加时间戳Options: -h,
- --help output usage information - V,
- --version output the version number
表示我们的命令行编写成功了!
大功告成了!可以开一瓶 82 年的雪碧庆祝下了!!!
等等,我觉的还是要发布到 npm 给兄弟们共享下劳动成果的,
那么怎么发布到 NPM 上呢?
首先你的有个 NPM 的账号吧
1,注册 NPM 账号
- $ npm adduser Username: river.cao Password: Email: river@gmail.com
2. 回到 timestamp 根目录 执行 npm publish , 如果没有错误提示那么就发布成果了,去 上看一下吧,你的模块应该已经显示在 "Latest Updates" 一栏里了。(当然肯出会错,因为模块名称已经被占用了)
那么 nodejs 的命令行开发已经讲完了,可以去喝雪碧了
来源: http://www.cnblogs.com/yingcaiyi/p/5920905.html