运行环境
将regedit的 vbs 文件夹拷贝到程序根目录下的resources目录里,这个目录名不能修改。
发行环境
原版json配置
css
"extraResources": [
{
"from": "node_modules/regedit/vbs",
"to": "vbs",
"filter": [
"**/*"
]
}
]
按照原版的json配置转yml配置就是这样的
electron-builder.yml 中配置
vbnet
extraResources:
- from: node_modules/regedit/vbs
to: vbs
filter:
- "**/*"
使用
javascript
import { readFileSync, existsSync } from 'fs'
import { spawn } from 'child_process'
import regedit from 'regedit'
const { promisified } = regedit
regedit.setExternalVBSLocation('./resources/vbs');
// 监听测试事件
ipcMain.on('test', async () => {
console.log('主进程测试')
try {
const qianniuPath = await getQianniuPath()
console.log('启动千牛工作台路径:', qianniuPath)
const child = spawn(qianniuPath, {
shell: true
})
child.on('error', (err) => {
console.error('启动千牛工作台失败:', err)
})
child.on('spawn', () => {
console.log('千牛工作台已启动')
})
} catch (error) {
console.error('获取千牛路径失败:', error)
}
})
// 新增注册表路径常量
const QIANNIU_REG_PATHS = [
'HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall',
'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall' // 确保包含标准Uninstall路径
]
// 修改获取千牛路径的方法
async function getQianniuPath(): Promise<string> {
try {
// 注册表路径配置说明:
// QIANNIU_REG_PATHS - 基础注册表搜索路径(包含32/64位系统路径)
// EXTRA_PATHS - 扩展搜索路径配置说明:
// 1. Wow6432Node下的AliWorkbench(兼容旧版安装路径)
// 2. 精确匹配路径(根据实际注册表结构添加)
const EXTRA_PATHS = [
'HKLM\SOFTWARE\Wow6432Node\AliWorkbench',
'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\千牛工作台'
]
// 异步读取注册表项列表(使用promisified接口)
// 组合路径策略:基础路径 + 扩展路径 = 完整的搜索范围
const keys = await promisified.list([...QIANNIU_REG_PATHS, ...EXTRA_PATHS])
// ================== 精确路径优先匹配策略 ==================
// 目标路径:专业版千牛的标准注册表项
const precisePath = 'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\千牛工作台'
// 检查精确路径是否存在(keys对象包含所有找到的注册表项)
if (keys[precisePath]) {
// 异步读取精确路径下的注册表值(注意:list方法需要接收数组参数)
const result = await promisified.list([precisePath])
// 解构赋值获取values对象(包含该注册表项的所有值)
const values = result[precisePath]?.values
// 路径处理逻辑:
// 1. 检查InstallLocation是否存在
// 2. 处理值类型(注册表值可能是REG_SZ或REG_EXPAND_SZ)
// 3. 移除路径中的双引号(应对带空格的路径)
if (values?.InstallLocation?.value) {
// 类型安全处理:
// - 字符串类型:直接替换双引号
// - 其他类型:转换为字符串处理(如REG_EXPAND_SZ展开后的系统路径)
const installPath = typeof values.InstallLocation.value === 'string'
? values.InstallLocation.value.replace(/"/g, '')
: String(values.InstallLocation.value)
// 构建完整可执行文件路径
const exePath = path.join(installPath, 'AliWorkbench.exe')
// 验证路径有效性(避免注册表数据与文件系统不一致)
if (existsSync(exePath)) {
console.log('通过精确路径找到千牛:', exePath) // <- 用户标记的代码行
return exePath
}
}
}
} catch (error) {
// 错误处理策略:
// 1. 记录原始错误信息
// 2. 抛出业务层可识别的错误类型
console.error('注册表读取失败:', error)
}
// 统一错误抛出(所有路径查找失败后的最终处理)
throw new Error('未找到千牛工作台路径')
}