forked from lioensky/VCPToolBox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtvsManager.js
More file actions
93 lines (82 loc) · 3.21 KB
/
Copy pathtvsManager.js
File metadata and controls
93 lines (82 loc) · 3.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// modules/tvsManager.js
const fs = require('fs').promises;
const path = require('path');
const chokidar = require('chokidar');
let TVS_DIR = path.join(__dirname, '..', 'TVStxt');
class TvsManager {
constructor() {
this.contentCache = new Map();
this.debugMode = false;
}
setTvsDir(dirPath) {
TVS_DIR = dirPath;
}
initialize(debugMode = false) {
this.debugMode = debugMode;
console.log('[TvsManager] Initializing...');
this.watchFiles();
}
watchFiles() {
try {
const watcher = chokidar.watch(TVS_DIR, {
ignored: [
'**/node_modules/**',
'**/.git/**',
'**/dist/**',
'**/target/**',
'**/image/**',
'**/.*'
],
persistent: true,
ignoreInitial: true, // Don't trigger 'add' events on startup
});
watcher
.on('change', (filePath) => {
const filename = path.basename(filePath);
if (this.contentCache.has(filename)) {
this.contentCache.delete(filename);
console.log(`[TvsManager] Cache for '${filename}' cleared due to file change.`);
}
})
.on('unlink', (filePath) => {
const filename = path.basename(filePath);
if (this.contentCache.has(filename)) {
this.contentCache.delete(filename);
console.log(`[TvsManager] Cache for '${filename}' cleared due to file deletion.`);
}
})
.on('error', (error) => console.error(`[TvsManager] Watcher error: ${error}`));
if (this.debugMode) {
console.log(`[TvsManager] Watching for changes in: ${TVS_DIR}`);
}
} catch (error) {
console.error(`[TvsManager] Failed to set up file watcher:`, error);
}
}
async getContent(filename) {
if (this.contentCache.has(filename)) {
if (this.debugMode) {
console.log(`[TvsManager] Cache hit for '${filename}'.`);
}
return this.contentCache.get(filename);
}
if (this.debugMode) {
console.log(`[TvsManager] Cache miss for '${filename}'. Reading from disk.`);
}
try {
const filePath = path.join(TVS_DIR, filename);
const content = await fs.readFile(filePath, 'utf8');
this.contentCache.set(filename, content);
return content;
} catch (error) {
// Don't cache errors, so it can be retried if the file appears later.
console.error(`[TvsManager] Error reading file '${filename}':`, error.message);
if (error.code === 'ENOENT') {
return `[变量文件 (${filename}) 未找到]`;
}
return `[处理变量文件 (${filename}) 时出错]`;
}
}
}
const tvsManager = new TvsManager();
module.exports = tvsManager;