nodejs 編寫(新增時間戳記)命令列工具 timestamp

來源:互聯網
上載者:User

標籤:

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 nodevar 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 adduserUsername:river.caoPassword:Email:[email protected]

2.回到 timestamp 根目錄 執行 npm publish ,如果沒有錯誤提示那麼就發布成果了,去 http://search.npmjs.org/上看一下吧,你的模組應該已經顯示在”Latest Updates”一欄裡了。(當然肯出會錯,因為模組名稱已經被佔用了)

 

那麼 nodejs 的命令列開發已經講完了,可以去喝雪碧了

nodejs 編寫(新增時間戳記)命令列工具 timestamp

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.