-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdir_scanner.js
More file actions
74 lines (69 loc) · 2.45 KB
/
Copy pathdir_scanner.js
File metadata and controls
74 lines (69 loc) · 2.45 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
const fs = require('fs').promises;
const path = require('path');
const csvWriter = require('csv-writer').createObjectCsvWriter;
const config = require('./config.json');
async function scanDirectory(dirPath, depth = 0, maxDepth) {
if (depth > maxDepth) return [];
let results = [];
try {
const items = await fs.readdir(dirPath, { withFileTypes: true });
for (const item of items) {
const fullPath = path.join(dirPath, item.name);
const result = {
name: item.name,
path: fullPath,
type: item.isDirectory() ? 'directory' : 'file',
extension: item.isFile() ? path.extname(item.name).toLowerCase() : '',
size: item.isFile() ? (await fs.stat(fullPath)).size : 0,
timestamp: new Date().toISOString()
};
if (item.isDirectory()) {
const subResults = await scanDirectory(fullPath, depth + 1, maxDepth);
results = [...results, result, ...subResults];
} else if (config.extensions.length === 0 || config.extensions.includes(result.extension)) {
results.push(result);
}
}
return results;
} catch (error) {
if (config.retryCount > 0) {
await new Promise(resolve => setTimeout(resolve, config.retryDelayMs));
return scanDirectory(dirPath, depth, maxDepth, config.retryCount - 1);
}
results.push({
name: path.basename(dirPath),
path: dirPath,
type: 'error',
extension: '',
size: 0,
timestamp: new Date().toISOString(),
error: error.message
});
return results;
}
}
async function saveResults(results) {
await fs.writeFile('scan_results.json', JSON.stringify(results, null, 2));
const csv = csvWriter({
path: 'scan_results.csv',
header: [
{ id: 'name', title: 'Name' },
{ id: 'path', title: 'Path' },
{ id: 'type', title: 'Type' },
{ id: 'extension', title: 'Extension' },
{ id: 'size', title: 'Size (Bytes)' },
{ id: 'timestamp', title: 'Timestamp' },
{ id: 'error', title: 'Error' }
]
});
await csv.writeRecords(results);
}
async function main() {
const results = await scanDirectory(config.directory, 0, config.maxDepth);
console.log(`Scanned ${results.length} items.`);
await saveResults(results);
}
main().catch(async error => {
console.error('Error:', error.message);
await saveResults([{ name: 'N/A', path: config.directory, type: 'error', extension: '', size: 0, timestamp: new Date().toISOString(), error: error.message }]);
});