現(xiàn)在來模仿 node npm 包從下載到使用的全過程孵滞。我們要封裝一個(gè)功能函數(shù)锦担,這個(gè)功能函數(shù)可以返回當(dāng)天的年月日,模仿的是 npm 社區(qū)的 moment 包弦牡。然后我們自己寫的這個(gè)函數(shù)再通過 node 安裝到全局,在電腦上任何地方都能使用這個(gè)函數(shù)漂羊。
參考文檔:
- Commander.js中文文檔
- momen 今時(shí)今日的年月日
class moments{
constructor(date){
// 獲取時(shí)間對(duì)象的年月日
this.year = date.getFullYear();
this.day = date.getDate();
// 月份從零開始驾锰,當(dāng)前月份就得加一
this.month = date.getMonth() + 1;
// // 月份和天數(shù)小于十是各位數(shù)的時(shí)候,補(bǔ)零
// this.month = this.month > 10 ? this.month : `0${this.month}`;
// this.day = this.day > 10 ? this.day : `0${this.day}` ;
//上面補(bǔ)零的方法不太好現(xiàn)在使用ES6的語法
this.month = this.month.toString().padStart(2,0)
this.day = this.day.toString().padStart(2,0)
}
// 時(shí)間轉(zhuǎn)化
format(str){
this.str = str.replace(/(y+)/gi,this.year);
this.str = this.str.replace(/m+/gi,this.month);
this.str = this.str.replace(/d+/gi,this.day);
// 控制臺(tái)輸出結(jié)果
console.log(this.str);
}
}
const moment = function get(res){
return new moments(res);
}
// node 默認(rèn)暴露一個(gè)變量
module.exports = moment;
#!/usr/bin/env node
const program = require('commander');
//=======app.js文件引入main.js === node app.js運(yùn)行輸出結(jié)果
const moment = require("./main.js");
program
.version('2.0.1')
.action(()=>{
console.log("今天的日期為:");
moment(new Date()).format("YYYY年MM月DD日");
})
.parse(process.argv);
改變 package.json 身份證
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"commander": "^2.20.0",
"moment": "^2.24.0"
},
//下面的是重點(diǎn)
"bin": {
"getdate": "./app.js"
}
}
把文件安裝到全局:
npm install -g .
這時(shí)你就能夠在系統(tǒng)的任何位置打開 CMD 窗口走越,使用 getdate 命令了椭豫!
看一下版本號(hào),檢測(cè)是否安裝成功:
getdate --version
安裝成功使用方法也很簡(jiǎn)單直接:
直接 getdate 回車得到結(jié)果。