npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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)

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-size

Usage

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 including errors.

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/")
  • options (object, optional): Extra settings
    • maxDepth (number): Max recursion depth for local folders. Default: Infinity
    • followSymlinks (boolean): Whether to follow symlinks for local paths. Default: false
    • ignore (RegExp): Ignore any local file/folder whose path matches the pattern
    • bigint (boolean): Return sizes as bigint for local paths. Default: false
    • fs (object): Custom filesystem handler (must provide promise functions: lstat, stat, readdir, realpath)
    • timeoutMs (number): Timeout for remote HTTP requests. Default: 15000
    • remoteMaxDepth (number): Max recursion depth for remote directory traversal. Default: 20
    • remoteMaxUrls (number): Max number of remote URLs visited in a single call. Default: 2000
    • concurrency (number): Max concurrent remote requests. Default: 10
    • headers (object): Extra HTTP headers for remote requests
    • fetch (function): Custom fetch implementation override
    • onProgress (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-target

Windows (Command Prompt as Administrator, or Developer Mode enabled):

mkdir target
echo hello> target\file.txt
mklink /D link-to-target target

Then 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