@mznjs/core
v0.0.1
Published
Collect some useful function libraries
Readme
📦 @mznjs/core 使用文档
✅ 模块概览
该模块提供了多个功能子模块:
- cache() / config():缓存存储管理
- crypto:加密解密工具(SHA256、MD5、AES 加密/解密)
- time:时间处理工具(格式化、过期判断等)
- CacheManager:缓存过期管理辅助函数
- logger /
console/log:日志输出实例(consola)
🔧 安装方式
npm install @mznjs/core
# 或者
pnpm add @mznjs/core要求 Node.js ≥ 18.0
🧩 导出接口一览
| 接口名 | 类型 | 说明 |
|--------|------|------|
| config(config?: Partial) | function | 初始化全局缓存配置 |
| cache(): ExtendedUnstorage | function | 创建缓存实例 |
| crypto.encrypt(value: string, key?: string): string | function | AES 加密 |
| crypto.decrypt(value: string, key?: string): string | function | AES 解密 |
| crypto.md5(value: string): string | function | MD5 哈希 |
| crypto.sha256(value: string): string | function | SHA256 哈希 |
| time.timeFormat(timestamp?: number, fmt?: string): string | function | 时间戳格式化 |
| time.isExpired(expires?: expires): boolean | function | 判断是否已过期 |
| time.formatDeadTime(expires?: expires): resultOptions | function | 格式化过期时间 |
| logger | ConsolaInstance | 日志打印器 |
🧪 示例代码
1. 缓存模块使用
初始化配置并创建缓存实例
import { config, cache } from '@mznjs/core'
// 配置缓存选项
config({
timeSuffix: '_deadtime',
encryptKeys: ['token', 'userinfo'],
useItemRaw: false,
isEncrypt: true // 启用加密
})
const storage = cache()
// 设置带过期时间的缓存
await storage.set('username', 'john_doe', { ttl: 60 }) // 60秒后过期
// 获取缓存
const user = await storage.get<string>('username')
console.log(user) // 输出: john_doe
// 删除缓存
await storage.remove('username')
// 清空所有缓存
await storage.clear()获取所有缓存项 & 缓存信息
await storage.set('key1', 'value1')
await storage.set('key2', 'value2')
const allItems = await storage.all()
console.log(allItems)
// 输出类似: [ { key: 'key1', value: 'value1' }, { key: 'key2', value: 'value2' } ]
const info = await storage.info()
console.log(info)
// 输出类似: { size: 2 }2. 加密模块使用
AES 加密与解密
import { crypto } from '@mznjs/core'
const secretKey = 'my-secret-key'
const plainText = 'Sensitive data'
const encrypted = crypto.encrypt(plainText, secretKey)
console.log('Encrypted:', encrypted)
const decrypted = crypto.decrypt(encrypted, secretKey)
console.log('Decrypted:', decrypted)
// 输出: Sensitive dataMD5 和 SHA256 哈希
const input = 'hello world'
console.log(crypto.md5(input)) // 输出 MD5 哈希值
console.log(crypto.sha256(input)) // 输出 SHA256 哈希值3. 时间处理模块使用
时间戳格式化
import { time } from '@mznjs/core'
const timestamp = Date.now()
console.log(time.timeFormat(timestamp)) // 输出默认格式: "2024-07-10 14:23:45"
console.log(time.timeFormat(timestamp, 'yyyy年mm月dd日')) // 输出: "2024年07月10日"判断是否过期
const expireTime = time.formatDeadTime('1h') // 1小时后过期
console.log(expireTime)
// 输出: { msg: '', data: { ttl: 3600, expireTime: 1720612800 } }
const isExpired = time.isExpired(expireTime.data.expireTime!)
console.log(isExpired ? '已过期' : '未过期')自动识别时间戳单位
console.log(time.guessTimestampUnit(1720609200)) // 输出: seconds
console.log(time.guessTimestampUnit(1720609200000)) // 输出: milliseconds4. 日志模块使用
import { logger, log, console } from '@mznjs/core'
logger.info('This is an info message')
logger.warn('This is a warning message')
logger.error('This is an error message')
// 等价写法
log.info('Another info message')
console.warn('Another warn message')⚙️ 高级配置说明
UnstorageOptions 配置项详解
| 属性名 | 类型 | 默认值 | 描述 |
|--------|------|--------|------|
| driver | Driver | memory | 存储驱动(支持 memory、localStorage 等) |
| timeSuffix | string | _deadtime | 过期时间键名后缀 |
| encryptKeys | string[] | [] | 需要强制加密的键列表 |
| useItemRaw | boolean | false | 是否直接操作原始数据 |
| isEncrypt | boolean | false | 是否启用整体加密 |
示例:指定 localStorage 驱动
config({
driver: localStorageDriver, // 需要自行引入或实现
timeSuffix: '_expire',
encryptKeys: ['token']
})📌 注意事项
- 所有缓存操作返回
Promise,请使用await。 encryptKeys表示即使isEncrypt=false,这些字段也会被加密。set(key, value, ttl)中ttl单位为 秒,非毫秒。formatDeadTime()支持字符串格式如'1h','2d'等。
