switch-get-file-folder-size
v1.2.0
Published
A Node.js package to calculate file and folder sizes locally and remotely (HTTP/HTTPS directories)
Maintainers
Readme
switch-get-file-folder-size
A Node.js package to calculate file and folder sizes locally and remotely (HTTP/HTTPS directories) made by Switcher.faiz.
Installation
npm install switch-get-file-folder-sizeUsage
const { getSize, formatBytes } = require('switch-get-file-folder-size');ESM (import) usage
import { getSize, getSizeDetailed, formatBytes } from 'switch-get-file-folder-size';Examples
Local Relative Folder
const { getSize, formatBytes } = require('switch-get-file-folder-size');
const checkSize = async () => {
try {
const folderPath = "./test_folder";
const size = await getSize(folderPath);
console.log(`Total size: ${size} bytes`);
console.log(`Total size: ${formatBytes(size)}`);
} catch (error) {
console.error('Error:', error.message);
}
};
checkSize();Local Relative File
const { getSize, formatBytes } = require('switch-get-file-folder-size');
const checkSize = async () => {
try {
const folderPath = "./test_folder/hello.txt";
const size = await getSize(folderPath);
console.log(`Total size: ${size} bytes`);
console.log(`Total size: ${formatBytes(size)}`);
} catch (error) {
console.error('Error:', error.message);
}
};
checkSize();Local Absolute Folder
const { getSize, formatBytes } = require('switch-get-file-folder-size');
const checkSize = async () => {
try {
const folderPath = "D:\\Mobile projects\\TodolistMobileApp\\assets";
const size = await getSize(folderPath);
console.log(`Total size: ${size} bytes`);
console.log(`Total size: ${formatBytes(size)}`);
} catch (error) {
console.error('Error:', error.message);
}
};
checkSize();Local Absolute File
const { getSize, formatBytes } = require('switch-get-file-folder-size');
const checkSize = async () => {
try {
const folderPath = "D:\\Mobile projects\\TodolistMobileApp\\app.json";
const size = await getSize(folderPath);
console.log(`Total size: ${size} bytes`);
console.log(`Total size: ${formatBytes(size)}`);
} catch (error) {
console.error('Error:', error.message);
}
};
checkSize();Remote Folder
const { getSize, formatBytes } = require('switch-get-file-folder-size');
const checkSize = async () => {
try {
const folderPath = "http://192.168.1.102/assets/";
const size = await getSize(folderPath);
console.log(`Total size: ${size} bytes`);
console.log(`Total size: ${formatBytes(size)}`);
} catch (error) {
console.error('Error:', error.message);
}
};
checkSize();Remote File
const { getSize, formatBytes } = require('switch-get-file-folder-size');
const checkSize = async () => {
try {
const folderPath = "http://192.168.1.102/assets/images/Female.svg";
const size = await getSize(folderPath);
console.log(`Total size: ${size} bytes`);
console.log(`Total size: ${formatBytes(size)}`);
} catch (error) {
console.error('Error:', error.message);
}
};
checkSize();Remote File (HTTPS)
const { getSize, formatBytes } = require('switch-get-file-folder-size');
const checkSize = async () => {
try {
const file = "https://images.pexels.com/photos/35163027/pexels-photo-35163027.jpeg";
const size = await getSize(file);
console.log(`Total size: ${size} bytes`);
console.log(`Total size: ${formatBytes(size)}`);
} catch (error) {
console.error('Error:', error.message);
}
};
checkSize();Remote File with No Extension
const { getSize, formatBytes } = require('switch-get-file-folder-size');
const checkSize = async () => {
try {
const folderPath = "http://192.168.1.102/assets";
const size = await getSize(folderPath);
console.log(`Total size: ${size} bytes`);
console.log(`Total size: ${formatBytes(size)}`);
} catch (error) {
console.error('Error:', error.message);
}
};
checkSize();API
Error handling modes
This package supports three ways to handle read errors (especially useful when files are being modified while scanning):
getSize.strict(path, options?): returns the size and throws if an error occurs.getSize.loose(path, options?): returns the size and ignores read errors (size may be smaller than real size).getSize.report(path, options?): returns a detailed object includingerrors.
All of these methods work for local paths. For remote URLs, errors are thrown as usual.
getSize(inputPath, options?)
Calculates the size of a file or folder (local or remote).
Parameters:
inputPath(string): Path to the file or folder- Local paths: Relative (e.g.,
"./folder") or absolute (e.g.,"D:\\folder") - Remote paths: HTTP/HTTPS URLs (e.g.,
"http://example.com/folder/")
- Local paths: Relative (e.g.,
options(object, optional): Extra settingsmaxDepth(number): Max recursion depth for local folders. Default:InfinityfollowSymlinks(boolean): Whether to follow symlinks for local paths. Default:falseignore(RegExp): Ignore any local file/folder whose path matches the patternbigint(boolean): Return sizes asbigintfor local paths. Default:falsefs(object): Custom filesystem handler (must provide promise functions:lstat,stat,readdir,realpath)timeoutMs(number): Timeout for remote HTTP requests. Default:15000remoteMaxDepth(number): Max recursion depth for remote directory traversal. Default:20remoteMaxUrls(number): Max number of remote URLs visited in a single call. Default:2000concurrency(number): Max concurrent remote requests. Default:10headers(object): Extra HTTP headers for remote requestsfetch(function): Custom fetch implementation overrideonProgress(function): Progress callback for local/remote traversal
What these options mean (practical)
followSymlinks(local only)false(default): symlinks are treated like links and are not followed (safer; avoids loops).true: symlinks are followed, so the size of the symlink target is included.
maxDepth(local only)0: do not enter subfolders of the starting directory.1: include direct children, but not grandchildren.Infinity(default): traverse the full tree.
timeoutMs(remote only)- Maximum time allowed for a single HTTP request before aborting.
remoteMaxDepth/remoteMaxUrls(remote only)- Safety limits to prevent crawling very large or looping directory listings.
concurrency(remote only)- Limits how many remote requests can run at the same time.
Returns:
Promise<number>: Size in bytes
Throws:
- Error if the path is invalid or inaccessible
Options examples
const { getSize } = require('switch-get-file-folder-size');
// Local: avoid symlink loops, optional depth limit
const bytes1 = await getSize('./some-folder', { maxDepth: 50, followSymlinks: false });
// Local: ignore node_modules (regex)
const bytesIgnored = await getSize('./some-folder', { ignore: /node_modules/ });
// Local: use bigint
const bytesBig = await getSize.strict('./some-folder', { bigint: true });
// Remote: make it safer/faster for big directory listings
const bytes2 = await getSize('https://example.com/assets/', {
timeoutMs: 20000,
remoteMaxDepth: 10,
remoteMaxUrls: 1000,
concurrency: 8,
});
// Remote: with headers and progress callback
const bytes3 = await getSize('https://example.com/assets/', {
headers: { Authorization: 'Bearer <token>' },
onProgress: (e) => {
// e.type can be: local:entry, remote:file, remote:dir
// for remote events: e.url, e.depth
// for local events: e.path, e.depth
// console.log(e);
},
});Strict / Loose / Report examples
import { getSize } from 'switch-get-file-folder-size';
// strict: throws on read errors
const strictBytes = await getSize.strict('./some-folder');
// loose: ignores read errors
const looseBytes = await getSize.loose('./some-folder');
// report: returns errors list
const report = await getSize.report('./some-folder');
console.log(report.bytes, report.errors);getSizeDetailed(inputPath, options?)
Same as getSize, but returns extra metadata.
Returns:
{
bytes: number,
files: number,
dirs: number,
skipped: number
}Example:
const { getSizeDetailed, formatBytes } = require('switch-get-file-folder-size');
const result = await getSizeDetailed('./some-folder', { followSymlinks: false });
console.log(result.bytes, formatBytes(result.bytes));
console.log({ files: result.files, dirs: result.dirs, skipped: result.skipped });Symlink example (local)
Create a test folder + symlink, then compare followSymlinks: false vs true.
Linux/macOS:
mkdir -p target
echo hello > target/file.txt
ln -s target link-to-targetWindows (Command Prompt as Administrator, or Developer Mode enabled):
mkdir target
echo hello> target\file.txt
mklink /D link-to-target targetThen run:
const { getSize, formatBytes } = require('switch-get-file-folder-size');
const a = await getSize('./link-to-target', { followSymlinks: false });
const b = await getSize('./link-to-target', { followSymlinks: true });
console.log('followSymlinks=false:', a, formatBytes(a));
console.log('followSymlinks=true :', b, formatBytes(b));maxDepth examples (local)
const { getSize, formatBytes } = require('switch-get-file-folder-size');
// Only the starting directory (no children)
const d0 = await getSize('./some-folder', { maxDepth: 0 });
// Includes files/folders directly inside ./some-folder
const d1 = await getSize('./some-folder', { maxDepth: 1 });
// Full recursion (default)
const all = await getSize('./some-folder');
console.log({ d0: formatBytes(d0), d1: formatBytes(d1), all: formatBytes(all) });Remote safety/performance examples
const { getSize } = require('switch-get-file-folder-size');
// Safer crawl for large directory listings
const bytes = await getSize('https://example.com/assets/', {
timeoutMs: 15000,
remoteMaxDepth: 5,
remoteMaxUrls: 500,
concurrency: 4,
});formatBytes(bytes)
Converts bytes to a human-readable format.
Parameters:
bytes(number): Size in bytes
Returns:
string: Formatted string (e.g., "1.5 MB", "500 Bytes")
Features
- ✅ Calculate local file sizes
- ✅ Calculate local folder sizes (recursive)
- ✅ Calculate remote file sizes (HTTP/HTTPS)
- ✅ Calculate remote folder sizes (HTTP/HTTPS directory listings)
- ✅ Human-readable format conversion
- ✅ Supports both relative and absolute paths
- ✅ Automatic detection of files vs directories
Requirements
- Node.js >= 14.0.0
License
MIT
About
Made by Switcher.faiz
