83 lines
2.4 KiB
JavaScript
83 lines
2.4 KiB
JavaScript
const path = require('path');
|
||
const fs = require('fs');
|
||
const { app } = require('electron');
|
||
|
||
// 判断是否为开发环境
|
||
const isDev = process.env.NODE_ENV === 'development' || !app.isPackaged;
|
||
|
||
// 检测是否为便携模式
|
||
let isPortable = false;
|
||
let dataDir;
|
||
|
||
if (isDev) {
|
||
// 开发环境:数据存储在工程的data目录
|
||
dataDir = path.join(process.cwd(), 'data');
|
||
} else {
|
||
try {
|
||
// 关键修改:使用process.argv[0]获取实际启动路径
|
||
const exePath = process.argv[0];
|
||
let appDir = path.dirname(exePath);
|
||
|
||
console.log('实际可执行文件路径:', exePath);
|
||
console.log('实际应用目录:', appDir);
|
||
|
||
// 检测是否存在portable.txt标记文件
|
||
const portableFlagPath = path.join(appDir, 'portable.txt');
|
||
isPortable = fs.existsSync(portableFlagPath);
|
||
|
||
// 如果在临时目录中运行且未找到标记文件
|
||
const isTempDir = appDir.includes('Temp') || appDir.includes('tmp');
|
||
if (isTempDir && !isPortable) {
|
||
// 尝试通过遍历上级目录寻找portable.txt来确定实际应用目录
|
||
let currentDir = appDir;
|
||
// 最多向上查找5级目录
|
||
for (let i = 0; i < 5; i++) {
|
||
currentDir = path.dirname(currentDir);
|
||
const checkFlagPath = path.join(currentDir, 'portable.txt');
|
||
if (fs.existsSync(checkFlagPath)) {
|
||
appDir = currentDir;
|
||
isPortable = true;
|
||
console.log('在上级目录找到便携模式标记:', appDir);
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 设置数据目录为应用目录下的data文件夹
|
||
dataDir = path.join(appDir, 'data');
|
||
console.log('最终数据目录:', dataDir);
|
||
|
||
// 确保便携模式标记文件存在
|
||
if (isPortable) {
|
||
const flagPath = path.join(appDir, 'portable.txt');
|
||
if (!fs.existsSync(flagPath)) {
|
||
fs.writeFileSync(flagPath, '');
|
||
}
|
||
}
|
||
} catch (error) {
|
||
console.error('确定数据目录时出错:', error);
|
||
// 出错时使用应用数据目录作为后备
|
||
dataDir = path.join(app.getPath('userData'), 'data');
|
||
}
|
||
}
|
||
|
||
// 确保数据目录存在
|
||
if (!fs.existsSync(dataDir)) {
|
||
fs.mkdirSync(dataDir, { recursive: true });
|
||
console.log(`创建数据目录: ${dataDir}`);
|
||
}
|
||
|
||
// 系统数据库路径
|
||
function getSystemDbPath() {
|
||
return path.join(dataDir, 'system.db');
|
||
}
|
||
|
||
// 用户数据库路径
|
||
function getUserDbPath() {
|
||
return path.join(dataDir, 'user.db');
|
||
}
|
||
|
||
module.exports = {
|
||
getSystemDbPath,
|
||
getUserDbPath
|
||
}; |