f2e-server3
Version:
f2e-server 3.0
162 lines (161 loc) • 5.59 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DBFile = void 0;
const fs = __importStar(require("node:fs"));
const path = __importStar(require("node:path"));
const logger_1 = __importDefault(require("../logger"));
const defaults = {
flushInterval: 3000,
watchFile: false,
autoSave: false,
fileToData: (filePath) => JSON.parse(fs.readFileSync(filePath, 'utf8')),
dataToFile: (data) => JSON.stringify(data.toString(), null, 2),
onFileChange: () => { },
};
class DBFile {
options;
data;
save_timer;
watcher;
isUpdating = false;
lastUpdateTime = 0;
DEBOUNCE_TIME = 100; // 防抖时间,单位毫秒
constructor(options) {
this.options = {
...defaults,
...options,
};
const { filePath, initData, autoSave, dataToFile, fileToData, watchFile, } = this.options;
this.data = options.initData;
if (fs.existsSync(filePath)) {
this.data = fileToData?.(filePath);
}
else if (initData && dataToFile) {
const dirname = path.dirname(filePath);
if (!fs.existsSync(dirname)) {
fs.mkdirSync(dirname, { recursive: true });
}
fs.writeFileSync(filePath, dataToFile(initData));
}
if (watchFile) {
this.startWatching();
}
if (autoSave) {
// 根据持久化频率保存文件
this.save_timer = setInterval(() => {
if (this.isUpdating)
return;
try {
this.isUpdating = true;
fs.writeFileSync(filePath, dataToFile(this.data));
}
catch (error) {
logger_1.default.error('自动保存失败:', error);
}
finally {
this.isUpdating = false;
}
}, this.options.flushInterval);
}
}
startWatching = () => {
const { filePath, fileToData, onFileChange } = this.options;
this.watcher = fs.watch(filePath, (eventType) => {
if (eventType !== 'change' || this.isUpdating)
return;
const now = Date.now();
if (now - this.lastUpdateTime < this.DEBOUNCE_TIME)
return;
this.lastUpdateTime = now;
try {
this.isUpdating = true;
const oldData = this.data;
const newData = fileToData(filePath);
this.data = newData;
onFileChange(newData, oldData);
}
catch (error) {
logger_1.default.error('文件监听更新失败:', error);
}
finally {
this.isUpdating = false;
}
});
// 处理监听器错误
this.watcher.on('error', (error) => {
logger_1.default.error('文件监听错误:', error);
});
};
/**
* 修改数据并持久化,autoSave = true 时,仅修改数据,持久化使用定时器实现
* @param data 需要修改的数据,不提供不修改
* @returns
*/
update = (data) => {
if (data) {
this.data = data;
}
const { autoSave, filePath, dataToFile, flushInterval, } = this.options;
if (autoSave) {
// 自动保存模式下,不处理
return;
}
if (this.save_timer) {
clearTimeout(this.save_timer);
}
if (dataToFile) {
this.save_timer = setTimeout(() => {
this.isUpdating = true;
try {
fs.writeFileSync(filePath, dataToFile(this.data));
}
catch (error) {
logger_1.default.error('数据持久化失败:', error);
}
finally {
this.isUpdating = false;
}
}, flushInterval);
}
};
destroy = () => {
if (this.save_timer) {
if (this.options.autoSave) {
clearInterval(this.save_timer);
}
else {
clearTimeout(this.save_timer);
}
}
if (this.watcher) {
this.watcher.close();
}
};
}
exports.DBFile = DBFile;