UNPKG

fswin32

Version:

The ultimate Node.js module for detailed Windows file system access.

79 lines (71 loc) 2.8 kB
// src/folders.js import { promises as fs } from 'fs'; import path from 'path'; import os from 'os'; import { executePowerShellCommand, formatBytes } from './utils.js'; /** * Recursively calculates the size of a folder and counts its contents. * @param {string} folderPath The absolute path of the folder. * @returns {Promise<{totalSize: number, fileCount: number, folderCount: number}>} */ export const getFolderSizeAndCount = async (folderPath) => { let totalSize = 0; let fileCount = 0; let folderCount = 0; try { const items = await fs.readdir(folderPath, { withFileTypes: true }); for (const item of items) { const itemPath = path.join(folderPath, item.name); try { const stats = await fs.stat(itemPath); if (stats.isDirectory()) { folderCount++; const subFolderInfo = await getFolderSizeAndCount(itemPath); totalSize += subFolderInfo.totalSize; fileCount += subFolderInfo.fileCount; folderCount += subFolderInfo.folderCount; } else if (stats.isFile()) { fileCount++; totalSize += stats.size; } } catch (err) { /* Ignore inaccessible files/folders */ } } } catch (error) { /* Ignore inaccessible parent folder */ } return { totalSize, fileCount, folderCount }; }; /** * Gets detailed information about a specific folder. * @param {string} folderPath The absolute path of the folder. * @returns {Promise<Object|null>} An object with detailed information. */ export const getFolderDetails = async (folderPath) => { try { const stats = await fs.stat(folderPath); if (!stats.isDirectory()) { return null; // Not a folder } let owner = 'N/A'; const isWindows = os.platform() === 'win32'; if (isWindows) { const stdout = await executePowerShellCommand(`(Get-Item -Path "${folderPath}").GetAccessControl().Owner`); if (stdout) { owner = stdout.trim(); } } const { totalSize, fileCount, folderCount } = await getFolderSizeAndCount(folderPath); return { path: folderPath, name: path.basename(folderPath), is_folder: true, last_modified: stats.mtime, owner: owner, total_size_bytes: totalSize, total_size_formatted: formatBytes(totalSize), contains_files_count: fileCount, contains_folders_count: folderCount, }; } catch (error) { console.error(`Error getting details for ${folderPath}:`, error.message); return null; } };