nodejs 編寫(添加時間戳)命令行工具 timestamp

Nodejs除了編寫服務器端程序還能夠編寫命令行工具,如gulp.js就是Nodejs編寫的。css

接下來咱們來實現一個添加時間戳的命令: $ timestamp actionhtml

 

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

 

1.須要用的模塊:git

commander  模塊github

  • 用途 :解析命令行參數
  • 主頁: https://tj.github.io/commander.js/

fs 模塊web

  • 用途 :於對系統文件及目錄進行讀寫操做

2.命令格式npm

編寫命令行工具前,首先定義命令的使用方式:json

如:gulp

  • 項目文件目錄下 $ 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 的命令行開發已經講完了,能夠去喝雪碧了

相關文章
相關標籤/搜索