-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch-main.js
More file actions
376 lines (315 loc) · 9.94 KB
/
Copy pathsearch-main.js
File metadata and controls
376 lines (315 loc) · 9.94 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
const { app, BrowserWindow, ipcMain, dialog, shell } = require('electron');
const path = require('path');
const fs = require('fs').promises;
const fsSync = require('fs');
let mainWindow;
let searchAborted = false;
function createWindow() {
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
preload: path.join(__dirname, 'search-preload.js'),
nodeIntegration: false,
contextIsolation: true
}
});
mainWindow.loadFile('file-search.html');
// mainWindow.webContents.openDevTools(); // 开发调试时取消注释
}
app.whenReady().then(() => {
createWindow();
app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit();
});
// 选择文件夹
ipcMain.handle('select-folder', async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ['openDirectory']
});
if (!result.canceled && result.filePaths.length > 0) {
return result.filePaths[0];
}
return null;
});
// 搜索文件 - 优化版本
ipcMain.handle('search-files', async (event, options) => {
searchAborted = false;
const { folderPath, searchQuery, filters } = options;
try {
// 验证路径
const stats = await fs.stat(folderPath);
if (!stats.isDirectory()) {
throw new Error('指定的路径不是文件夹');
}
// 开始搜索
const searchContext = {
query: searchQuery,
filters: filters,
scannedCount: 0,
foundFiles: new Set(),
priorityDirs: [],
batchResults: [],
lastUpdateTime: Date.now()
};
await searchDirectoryOptimized(folderPath, searchContext, event);
// 发送剩余的批量结果
if (searchContext.batchResults.length > 0 && !searchAborted) {
event.sender.send('files-batch', searchContext.batchResults);
}
if (!searchAborted) {
event.sender.send('search-complete', {
totalFound: searchContext.foundFiles.size,
totalScanned: searchContext.scannedCount
});
}
} catch (error) {
event.sender.send('search-error', error.message);
}
});
// 停止搜索
ipcMain.handle('stop-search', () => {
searchAborted = true;
return true;
});
// 优化的递归搜索 - 使用批量处理和并行读取
async function searchDirectoryOptimized(dirPath, context, event, depth = 0) {
if (searchAborted) return;
try {
let entries;
try {
entries = await fs.readdir(dirPath, { withFileTypes: true });
} catch (error) {
if (error.code === 'EPERM' || error.code === 'EACCES') return;
throw error;
}
const files = [];
const directories = [];
// 快速分离文件和目录
for (const entry of entries) {
if (searchAborted) return;
if (entry.isDirectory()) {
if (shouldSkipDirectory(entry.name)) continue;
directories.push(path.join(dirPath, entry.name));
} else if (entry.isFile()) {
if (shouldSkipFile(entry.name)) continue;
files.push({ name: entry.name, path: path.join(dirPath, entry.name) });
}
}
// 批量处理文件
let foundInCurrentDir = false;
const matchedFiles = [];
for (const file of files) {
if (searchAborted) return;
context.scannedCount++;
if (matchesSearchCriteria(file, context)) {
if (context.foundFiles.has(file.path)) continue;
context.foundFiles.add(file.path);
foundInCurrentDir = true;
matchedFiles.push(file.path);
}
}
// 批量获取文件信息并发送
if (matchedFiles.length > 0) {
const fileInfoPromises = matchedFiles.map(filePath => getFileInfoFast(filePath));
const fileInfos = await Promise.all(fileInfoPromises);
for (const fileInfo of fileInfos) {
if (fileInfo && !searchAborted) {
context.batchResults.push(fileInfo);
}
}
}
// 批量发送结果 (每50个文件发送一次,减少IPC通信)
const now = Date.now();
if (context.batchResults.length >= 50 || now - context.lastUpdateTime > 1000) {
if (context.batchResults.length > 0 && !searchAborted) {
// 一次性发送所有批量结果
event.sender.send('files-batch', context.batchResults);
context.batchResults = [];
}
context.lastUpdateTime = now;
// 发送进度更新 (降低频率)
event.sender.send('search-progress', {
scannedCount: context.scannedCount,
currentPath: dirPath
});
}
// 优化算法: 如果在当前目录找到匹配文件,优先搜索子目录
if (foundInCurrentDir && context.query) {
context.priorityDirs.unshift(...directories);
}
// 并行搜索子目录 (增加并行数到5,提升速度)
const maxParallel = 5;
for (let i = 0; i < directories.length; i += maxParallel) {
if (searchAborted) return;
const batch = directories.slice(i, i + maxParallel);
const promises = batch.map(subDir => {
if (depth < 25) { // 增加深度限制
return searchDirectoryOptimized(subDir, context, event, depth + 1);
}
return Promise.resolve();
});
await Promise.all(promises);
}
// 处理优先目录队列
if (depth === 0 && context.priorityDirs.length > 0) {
const priorityDir = context.priorityDirs.shift();
if (priorityDir && !searchAborted) {
await searchDirectoryOptimized(priorityDir, context, event, 0);
}
}
} catch (error) {
if (error.code !== 'EPERM' && error.code !== 'EACCES') {
console.error(`无法访问目录 ${dirPath}:`, error.message);
}
}
}
// 判断是否应该跳过目录
function shouldSkipDirectory(dirName) {
const skipDirs = [
'node_modules', '.git', '.svn', '.hg',
'$RECYCLE.BIN', '$Recycle.Bin', 'System Volume Information',
'Windows', 'Program Files', 'Program Files (x86)',
'ProgramData', 'AppData', '.cache', '.npm',
'.vscode', '.idea', '__pycache__', 'Intel'
];
return skipDirs.includes(dirName) || dirName.startsWith('.') || dirName.startsWith('$');
}
// 判断是否应该跳过文件
function shouldSkipFile(fileName) {
const skipFiles = [
'pagefile.sys', 'swapfile.sys', 'hiberfil.sys',
'DumpStack.log.tmp', 'DumpStack.log'
];
return skipFiles.includes(fileName) || fileName.endsWith('.tmp');
}
// 匹配搜索条件
function matchesSearchCriteria(file, context) {
const fileName = file.name.toLowerCase();
const ext = path.extname(file.name).toLowerCase();
// 检查文件类型过滤
if (context.filters && context.filters.length > 0) {
if (!context.filters.includes(ext)) {
return false;
}
}
// 检查搜索查询
if (context.query) {
return fileName.includes(context.query);
}
return true;
}
// 快速获取文件信息 - 使用异步方法不阻塞主线程
async function getFileInfoFast(filePath) {
try {
const stats = await fs.stat(filePath);
const parsedPath = path.parse(filePath);
return {
name: parsedPath.base,
path: filePath,
dir: parsedPath.dir,
ext: parsedPath.ext,
size: stats.size,
mtime: stats.mtime,
birthtime: stats.birthtime,
atime: stats.atime
};
} catch (error) {
if (error.code !== 'EPERM' && error.code !== 'EACCES') {
console.error('获取文件信息失败:', error);
}
return null;
}
}
// 删除文件
ipcMain.handle('delete-files', async (event, { files }) => {
let successCount = 0;
let failCount = 0;
for (const file of files) {
try {
await fs.unlink(file.path);
successCount++;
} catch (err) {
console.error('Delete failed:', err);
failCount++;
}
// 发送进度
if ((successCount + failCount) % 10 === 0 || (successCount + failCount) === files.length) {
event.sender.send('delete-progress', {
current: successCount + failCount,
total: files.length
});
}
}
return { successCount, failCount };
});
// 导出文件
ipcMain.handle('export-files', async (event, { files, destFolder }) => {
let successCount = 0;
let failCount = 0;
// 限制并发数量
const limit = 10;
let active = 0;
let index = 0;
return new Promise((resolve) => {
const next = async () => {
if (index >= files.length) {
if (active === 0) {
resolve({ successCount, failCount });
}
return;
}
const file = files[index++];
active++;
try {
let targetPath = path.join(destFolder, file.name);
// 处理文件名冲突
let counter = 1;
while (fsSync.existsSync(targetPath)) {
const parsed = path.parse(file.name);
targetPath = path.join(destFolder, `${parsed.name} (${counter})${parsed.ext}`);
counter++;
}
// 使用原生的 copyFile,它在底层使用高效的系统调用
await fs.copyFile(file.path, targetPath, fsSync.constants.COPYFILE_FICLONE);
successCount++;
} catch (err) {
console.error('Copy failed:', err);
failCount++;
} finally {
active--;
// 发送进度
if ((successCount + failCount) % 10 === 0 || (successCount + failCount) === files.length) {
event.sender.send('export-progress', {
current: successCount + failCount,
total: files.length
});
}
next();
}
};
for (let i = 0; i < limit && i < files.length; i++) {
next();
}
});
});
// 打开文件夹
ipcMain.handle('open-folder', async (_event, folderPath) => {
try {
await shell.openPath(folderPath);
} catch (error) {
console.error('打开文件夹失败:', error);
}
});
// 打开文件
ipcMain.handle('open-file', async (_event, filePath) => {
try {
await shell.openPath(filePath);
} catch (error) {
console.error('打开文件失败:', error);
}
});