UNPKG

fast-dir-size

Version:

Calculates the total size of a folder and its subfolders.

53 lines (52 loc) 1.89 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getDirSizeSync = exports.getDirSize = void 0; const fs_1 = require("fs"); const path_1 = require("path"); const index_1 = require("./promises/index"); exports.getDirSize = index_1.default; const getFileSize = (filePath, callback) => { try { const fileStats = (0, fs_1.statSync)(filePath); return fileStats.size; } catch (error) { typeof callback === 'function' && callback(error); return 0; } }; const getDirEntries = (dirPath, callback) => { try { return (0, fs_1.readdirSync)(dirPath, { withFileTypes: true }); } catch (error) { typeof callback === 'function' && callback(error); return []; } }; const calculateTotalDirSize = (dirPath, callback) => { let totalSize = 0; const entries = getDirEntries(dirPath, callback); const len = entries.length; for (let i = 0; i < len; i += 1) { const entryPath = (0, path_1.join)(dirPath, entries[i].name); totalSize += entries[i].isDirectory() ? calculateTotalDirSize(entryPath, callback) : getFileSize(entryPath, callback); } return totalSize; }; /** * Calculates the total size of a folder and its subfolders. * @param {string} dirPath - The path to the folder. * @param {function} callback - A callback function that handles potential errors during the folder size calculation. * @returns {number} - The total size in bytes. * @throws {TypeError} - Throws an error if the provided path is not a string. * @since v1.2.0 */ const getDirSizeSync = (dirPath, callback) => { if (typeof dirPath !== 'string') { throw new TypeError(`Path must be a string. Received: ${typeof dirPath}`); } return calculateTotalDirSize(dirPath, callback); }; exports.getDirSizeSync = getDirSizeSync;