现在来模仿 node npm 包从下载到使用的全过程。我们要封装一个功能函数,这个功能函数可以返回当天的年月日,模仿的是 npm 社区的 moment 包。然后我们自己写的这个函数再通过 node 安装到全局,在电脑上任何地方都能使用这个函数。
参考文档:
- Commander.js中文文档
- momen 今时今日的年月日
class moments{
constructor(date){
// 获取时间对象的年月日
this.year = date.getFullYear();
this.day = date.getDate();
// 月份从零开始,当前月份就得加一
this.month = date.getMonth() + 1;
// // 月份和天数小于十是各位数的时候,补零
// this.month = this.month > 10 ? this.month : `0${this.month}`;
// this.day = this.day > 10 ? this.day : `0${this.day}` ;
//上面补零的方法不太好现在使用ES6的语法
this.month = this.month.toString().padStart(2,0)
this.day = this.day.toString().padStart(2,0)
}
// 时间转化
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);
// 控制台输出结果
console.log(this.str);
}
}
const moment = function get(res){
return new moments(res);
}
// node 默认暴露一个变量
module.exports = moment;
#!/usr/bin/env node
const program = require('commander');
//=======app.js文件引入main.js === node app.js运行输出结果
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"
},
//下面的是重点
"bin": {
"getdate": "./app.js"
}
}
把文件安装到全局:
npm install -g .
这时你就能够在系统的任何位置打开 CMD 窗口,使用 getdate 命令了!
看一下版本号,检测是否安装成功:
getdate --version
安装成功使用方法也很简单直接:
直接 getdate 回车得到结果。