1. 环境变量读取秘钥
PART1: 如何在powershell中读取环境变量
- 读取范围: 无论①用户环境 ②系统环境 变量都可以读取到
- 更新延迟: 注意idea要重启, 才能(在idea代码中)读取到
![]() |
|---|
[Environment]::GetEnvironmentVariable("FEISHU_APPID","User")
$env:FEISHU_APPSECRET
PART2: 如何在TS中读取环境变量
这个也是TS中运行powershell的方法
private readWindowsEnvironmentVariable(variableName: string, target: 'User' | 'Machine') {
const readCommand = `[Environment]::GetEnvironmentVariable('${variableName}','${target}')`
try {
const variableValue = execFileSync('powershell.exe', ['-NoProfile', '-Command', readCommand], {
encoding: 'utf8',
windowsHide: true
}).trim() // 每次读取都实时从 Windows 当前配置取值,保证用户刚修改环境变量后无需依赖 process.env 刷新
return variableValue
} catch (error) {
// 把读取失败的目标层级一并打印出来,便于区分是 User 还是 Machine 读取失败
console.error(`[feishu] Failed to read Windows ${target} env ${variableName}:`, error)
return ''
}
}
private readFeiShuCredential(variableName: 'FEISHU_APPID' | 'FEISHU_APPSECRET') {
const userVariableValue = this.readWindowsEnvironmentVariable(variableName, 'User')
if (userVariableValue) return userVariableValue
const machineVariableValue = this.readWindowsEnvironmentVariable(variableName, 'Machine')
return machineVariableValue
}
2. Electron的Store
import Store from 'electron-store'
// 本机文件位置: /Users/xi/Library/Application Support/electron-app/config.json
// electron-store@^8.2.0
class StoreManager {
private store: Store;
constructor() {
this.store = new Store();
}
/**
* 写入缓存
* @param key 缓存键
* @param value 缓存值
* @param expireTime 绝对过期时间戳,单位毫秒;不传则表示不过期
* @returns void
*/
setCache(key: string, value: any, expireTime?: number) { // 第三个参数统一解释为绝对过期时间戳,避免和调用方的时间语义不一致
if (expireTime && expireTime > 0) { // 显式传入过期时间时写入包装结构,供读取时校验是否过期
this.store.set(key, { value, expireTime }); // 直接保存绝对过期时间,避免再次叠加 Date.now() 造成时间失真
} else this.store.set(key, value); // 未传过期时间时按普通值直接落盘
}
/**
* 读取缓存
* @param key 缓存键
* @returns 原始缓存值;过期时返回 null
*/
getCache(key: string) { // 读取时统一向业务层返回原始值,避免把内部包装对象暴露出去
const cache: any = this.store.get(key); // 先读取一次原始缓存结果,兼容普通值和带过期时间的包装结构
if (cache && cache?.expireTime && cache?.expireTime < Date.now()) { // 命中过期包装对象时立即删除,避免继续返回旧值
this.store.delete(key); // 清理过期缓存,保证下次读取时不会继续命中过期数据
return null; // 过期后返回空值,交由上层决定是否重新拉取或重新认证
}
if (cache && cache?.expireTime) return cache.value; // 未过期的包装对象只向外暴露原始 value,避免调用方拿到整个包装对象
return cache; // 普通值按原样返回,保持既有调用方式不变
}
deleteCache(key: string) {
this.store.delete(key);
}
clearCache() {
this.store.clear();
}
}
export const storeManager = new StoreManager()
- Title:
- Author: 明廷盛
- Created at : 2026-06-28 07:47:04
- Updated at : 2026-06-28 07:47:04
- Link: https://blog.20040424.xyz/2026/06/28/😼Java全栈工程师/7. 前端部分/5.Electron开发零碎技术/
- License: All Rights Reserved © 明廷盛
