首页 技术 正文
技术 2022年11月10日
0 收藏 331 点赞 4,386 浏览 3698 个字

Nodejs除了编写服务器端程序还可以编写命令行工具,如gulp.js就是Nodejs编写的。

接下来我们来实现一个添加时间戳的命令: $ timestamp action

https://www.npmjs.com/package/timestamp007

1.需要用的模块:

commander  模块

  • 用途 :解析命令行参数
  • 主页: https://tj.github.io/commander.js/

fs 模块

  • 用途 :于对系统文件及目录进行读写操作

2.命令格式

编写命令行工具前,首先定义命令的使用方式:

如:

  • 项目文件目录下 $ timestamp action  表示项目下所有页面将添加时间戳
  • 给某个页面添加时间戳 $ timestamp action /project/index.html  
  • 在非项目录下运行 需要制定项目目录 $ timestamp action /Users/river/web

3.常见的命令格式

command [options] [arguments]

含义如下:

  • command:命令名称,如:node,timestamp
  • options:–单词或者单字母,比如–help 或者 –h
  • arguments :参数

在查看命令帮助时会出现  [],<>,|  等符号,他们的含义分别是

  • []:可选
  • <>:表示可变选项。一般是多选一。而且是必选其中一个。
  • X|Y|Z 多选一,如果加上[],则可不选。
  • -abc:多选,如果加上[], 则可不选。

如 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();
});
  • command(“help”)表示当前是什么命令
  • .description(‘显示使用帮助’) 当前的命令
  • .action(callback);解析到当前命令执行的回调函数
  • progarm.parse(process.argv)开始解析命令

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 ,如果没有错误提示那么就发布成果了,去 http://search.npmjs.org/上看一下吧,你的模块应该已经显示在”Latest Updates”一栏里了。(当然肯出会错,因为模块名称已经被占用了)

3.$ npm login  //如果已经有账号。可以用login命令重新登录npm

那么 nodejs 的命令行开发已经讲完了,可以去喝雪碧了

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,941
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,465
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,280
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,094
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,728
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,765