UNPKG

@ethersphere/bee-js

Version:
71 lines (70 loc) 2.47 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getFolderSize = exports.makeCollectionFromFS = void 0; const fs_1 = __importDefault(require("fs")); const path_1 = __importDefault(require("path")); /** * Creates array in the format of Collection with data loaded from directory on filesystem. * * @param dir path to the directory */ async function makeCollectionFromFS(dir) { if (typeof dir !== 'string') { throw new TypeError('dir has to be string!'); } if (dir === '') { throw new TypeError('dir must not be empty string!'); } return buildCollectionRelative(dir, ''); } exports.makeCollectionFromFS = makeCollectionFromFS; async function buildCollectionRelative(dir, relativePath) { const dirname = path_1.default.join(dir, relativePath); const entries = await fs_1.default.promises.opendir(dirname); let collection = []; for await (const entry of entries) { const fullPath = path_1.default.join(dir, relativePath, entry.name); const entryPath = path_1.default.join(relativePath, entry.name); if (entry.isFile()) { collection.push({ path: entryPath, size: (await fs_1.default.promises.stat(fullPath)).size, fsPath: fullPath, }); } else if (entry.isDirectory()) { collection = [...(await buildCollectionRelative(dir, entryPath)), ...collection]; } } return collection; } /** * Calculate folder size recursively * * @param dir the path to the folder to check * @returns size in bytes */ async function getFolderSize(dir) { if (typeof dir !== 'string') { throw new TypeError('dir has to be string!'); } if (dir === '') { throw new TypeError('dir must not be empty string!'); } const entries = await fs_1.default.promises.opendir(dir); let size = 0; for await (const entry of entries) { if (entry.isFile()) { const stats = await fs_1.default.promises.stat(path_1.default.join(dir, entry.name)); size += stats.size; } else if (entry.isDirectory()) { size += await getFolderSize(path_1.default.join(dir, entry.name)); } } return size; } exports.getFolderSize = getFolderSize;