UNPKG

ovm

Version:

OVM is a CLI application for managing Obsidian vaults.

97 lines 3.85 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getFileSize = exports.convertSizeToReadableUnit = void 0; const node_fs_1 = require("node:fs"); const node_path_1 = require("node:path"); const logger_1 = require("./logger"); const convertSizeToReadableUnit = (size) => { const units = ['B', 'KB', 'MB', 'GB']; let index = 0; let value = Number(size); while (value >= 1024 && index < units.length - 1) { value /= 1024; index++; } if (value === 0) { return `0 ${units[index]}`; } return `${value.toFixed(2)} ${units[index]}`; }; exports.convertSizeToReadableUnit = convertSizeToReadableUnit; const getFileSize = async (path, concurrency = 64, humanReadable = false) => { let stat; try { stat = await node_fs_1.promises.stat(path, { bigint: true }); if (!stat.isDirectory()) { throw new Error(`Path "${path}" is not a directory`); } } catch (err) { const typedError = err; if (typedError.code === 'ENOENT') { throw new Error(`Path "${path}" does not exist`); } throw new Error(`Failed to access path "${path}": ${typedError.message}`); } let size = 0n; const queue = [path]; const childLogger = logger_1.logger.child({ path }); const processQueue = async () => { while (queue.length > 0) { const currentPath = queue.shift(); let entries; try { entries = await node_fs_1.promises.readdir(currentPath, { withFileTypes: true }); } catch (err) { const typedError = err; childLogger.warn(`Failed to read directory`, { cause: typedError.message, }); continue; } const batchSize = Math.max(1, Math.floor(concurrency / 4)); for (let i = 0; i < entries.length; i += batchSize) { const batch = entries.slice(i, i + batchSize); const results = await Promise.allSettled(batch.map(async (entry) => { const fullPath = (0, node_path_1.join)(currentPath, entry.name); const stats = await node_fs_1.promises.stat(fullPath, { bigint: true }); if (stats.isFile()) { return { type: 'file', size: stats.size }; } else if (stats.isDirectory()) { return { type: 'directory', path: fullPath }; } return { type: 'other' }; })); results.forEach((result) => { if (result.status === 'fulfilled') { const value = result.value; if (value.type === 'file') { size += value?.size ?? 0n; } else if (value.type === 'directory') { queue.push(value?.path ?? ''); } } else { childLogger.warn(`Failed to process entry`, { cause: result.reason instanceof Error ? result.reason.message : String(result.reason), }); } }); } } }; const workers = Math.min(Math.max(1, concurrency), 16); const workerPromises = Array.from({ length: workers }, () => processQueue()); await Promise.allSettled(workerPromises); if (humanReadable) { return (0, exports.convertSizeToReadableUnit)(size); } return size; }; exports.getFileSize = getFileSize; //# sourceMappingURL=fs.js.map