Directory Operations & File System Programming
Deze pagina behandelt advanced directory operations, file system programming, en data organization strategies voor web development en server-side applications. ReadDir operations vormen de foundation voor file explorers, content management systems, en dynamic file serving applications. Modern file system APIs in Node.js, Python, PHP, en client-side JavaScript bieden comprehensive tools voor directory traversal, file metadata extraction, en secure file operations.
Modern Directory Listing Implementations
Contemporary directory listing implementations require efficient algorithms voor large directory structures, recursive traversal capabilities, en security-conscious file access controls. Streaming APIs prevent memory exhaustion bij large directories, terwijl pagination enables responsive user interfaces voor directory browsing. File metadata enrichment including MIME type detection, file size formatting, en modification timestamps enhance user experience en administrative functionality.
Security & Performance Considerations
File system security includes path traversal prevention, access control validation, en sanitization van user-provided paths. Performance optimization strategies include caching frequently accessed directory listings, implementing file watchers voor real-time updates, en efficient sorting algorithms voor large datasets. Cross-platform compatibility ensures consistent behavior across Windows, macOS, en Linux environments, crucial voor production deployments.
Advanced Directory Operations
// Node.js Advanced Directory Reader
import { promises as fs } from 'fs';
import path from 'path';
import { Worker } from 'worker_threads';
import EventEmitter from 'events';
class AdvancedDirectoryReader extends EventEmitter {
constructor(options = {}) {
super();
this.options = {
recursive: false,
includeHidden: false,
sortBy: 'name', // name, size, modified, type
sortOrder: 'asc',
concurrent: 5,
cache: true,
watchChanges: false,
...options
};
this.cache = new Map();
this.watchers = new Map();
}
async readDirectory(dirPath, options = {}) {
const opts = { ...this.options, ...options };
const normalizedPath = path.normalize(dirPath);
// Security: Validate path
if (!this.isPathSafe(normalizedPath)) {
throw new Error('Invalid or unsafe path provided');
}
// Check cache
if (opts.cache && this.cache.has(normalizedPath)) {
const cached = this.cache.get(normalizedPath);
if (Date.now() - cached.timestamp < 30000) { // 30s cache
return cached.data;
}
}
try {
const results = await this.processDirectory(normalizedPath, opts);
// Cache results
if (opts.cache) {
this.cache.set(normalizedPath, {
data: results,
timestamp: Date.now()
});
}
// Setup watcher if requested
if (opts.watchChanges && !this.watchers.has(normalizedPath)) {
this.setupWatcher(normalizedPath);
}
this.emit('directoryRead', normalizedPath, results);
return results;
} catch (error) {
this.emit('error', error, normalizedPath);
throw error;
}
}
async processDirectory(dirPath, options) {
const items = await fs.readdir(dirPath, { withFileTypes: true });
const results = [];
// Process items concurrently
const chunks = this.chunkArray(items, options.concurrent);
for (const chunk of chunks) {
const promises = chunk.map(item => this.processItem(dirPath, item, options));
const chunkResults = await Promise.all(promises);
results.push(...chunkResults.filter(Boolean));
}
// Sort results
return this.sortItems(results, options.sortBy, options.sortOrder);
}
}
// Directory Component for React Applications
const DirectoryExplorer = ({ rootPath, onFileSelect }) => {
const [currentPath, setCurrentPath] = useState(rootPath);
const [items, setItems] = useState([]);
const [loading, setLoading] = useState(false);
const [sortBy, setSortBy] = useState('name');
const [viewMode, setViewMode] = useState('list'); // list or grid
const reader = useRef(new AdvancedDirectoryReader());
useEffect(() => {
loadDirectory(currentPath);
}, [currentPath, sortBy]);
const loadDirectory = async (path) => {
setLoading(true);
try {
const result = await reader.current.readDirectory(path, {
sortBy: sortBy,
includeHidden: false
});
setItems(result);
} catch (error) {
console.error('Failed to load directory:', error);
} finally {
setLoading(false);
}
};
return (
{currentPath}
{loading ? (
Loading directory...
) : (
{items.map(item => (
{
if (item.type === 'directory') {
setCurrentPath(item.path);
} else {
onFileSelect?.(item);
}
}}
>
{item.type === 'directory' ? '📁' : '📄'}
{item.name}
{item.type === 'file' && (
{formatFileSize(item.size)}
)}
{new Date(item.modified).toLocaleDateString()}
))}
)}
);
};
Real-time Directory Monitoring
Advanced directory operations include real-time monitoring capabilities using file system watchers, WebSocket connections voor live updates, en event-driven architectures. Integration met version control systems enables tracking van file changes, commit history integration, en automated backup triggers. Cloud storage synchronization, FTP/SFTP integration, en distributed file systems require specialized handling voor network latency, connection reliability, en data consistency across multiple environments.