filesize.js Documentation

repository·master·Indexed 23 days ago

https://github.com/avoidwork/filesize.js

A lightweight, zero-dependency JavaScript utility (v11.0.22) for converting bytes or bits into human-readable strings. It supports BigInt, localization, and multiple unit standards including SI, IEC, and JEDEC. The library provides flexible output formats (string, array, object, or exponent) and a partial() function for creating reusable, pre-configured formatters.

Tokens
12.6K
Snippets
36
Records
56
Agent score
81%

What's inside filesize

  1. Overview of filesize

    master

    filesize is a modern JavaScript library designed to convert numeric byte values into human-readable file size strings. It is suitable for web applications, mobile apps, and cloud platforms.

    Key Features

    • Multiple Unit Standards: Supports SI (decimal), IEC (binary), and JEDEC standards.
    • Localization Support: Full internationalization with locale-specific formatting.
    • Flexible Output: Can return results as a String, Array, Object, or Exponent format.
    • BigInt Support: Capable of handling extremely large file sizes using BigInt.
    • Customizable Formatting: Control over precision, rounding, symbols, and spacing.
    • Functional Programming: Supports partial application for reusing configurations.

    Browser & Runtime Support

    • Node.js: 10.4.0+
    • Modern Browsers: Requires ES6+ support.
    • Mobile: iOS Safari 10+, Android Chrome 51+.
    • Server Environments: Deno, Bun, Cloudflare Workers.
  2. How bits conversion works

    master

    When converting to bits instead of bytes (e.g., when bits: true is passed), the library follows these steps:

    1. Base Value Calculation: Calculates the value using the standard byte conversion formula: value = bytes / divisor[e].
    2. Bit Multiplication: Multiplies the resulting value by 8: value_bits = value * 8.
    3. Overflow Handling: If the resulting bit value reaches the ceiling of the current unit (e.g., 8192 Kbit), the library automatically increments the exponent to the next unit (e.g., 8 Mbit) to ensure proper unit progression.

    Examples

    • 1024 bytes (Decimal/Base 10): 1024 * 8 / 1000 = 8.192 $\rightarrow$ "8.19 kbit"
    • 1024 bytes (Binary/Base 2): 1024 * 8 / 1024 = 8 $\rightarrow$ "8 Kibit"
  3. Use different unit standards (SI, IEC, JEDEC)

    master

    The library supports three major standards for file size representation:

    • SI: Base 10 (e.g., kB, MB). This is the default.
    • IEC: Binary-based (base 2) using specific symbols (e.g., KiB, MiB). Requires base: 2 or standard: 'iec'.
    • JEDEC: Binary calculation using traditional symbols (e.g., KB, MB).
    // SI (default, base 10)
    filesize(1000); // "1 kB"
    
    // IEC (binary, requires base: 2)
    filesize(1024, {base: 2, standard: "iec"}); // "1 KiB"
    
    // JEDEC (binary calculation, traditional symbols)
    filesize(1024, {standard: "jedec"}); // "1 KB"
  4. Behavior of the partial function regarding deep cloning

    master

    The partial function implements safe deep cloning for all provided options. This ensures that the internal state of the returned function is isolated from the original objects or arrays passed during partial application. This behavior applies to:

    • Plain objects: e.g., localeOptions.
    • Symbols: e.g., symbols.
    • Arrays: e.g., fullforms.

    Modifying the configuration of the returned function will not mutate the original input objects.

  5. How filesize handles different unit standards

    master

    The library uses different mathematical bases to determine unit scales depending on the chosen standard:

    Binary Standard (IEC)

    Uses powers of 1024. This is used for units like B, KiB, MiB, GiB, TiB, PiB, EiB, ZiB, and YiB.

    Decimal Standard (SI/JEDEC)

    Uses powers of 1000. This is used for units like B, KB, MB, GB, TB, PB, EB, ZB, and YB (using JEDEC-style symbols).

    Mathematical Logic

    The library calculates the appropriate exponent ($e$) using the change of base formula: e = ⌊ln(bytes) / ln(base)⌋

    It then uses pre-computed lookup tables (BINARY_POWERS or DECIMAL_POWERS) to divide the bytes by the divisor corresponding to that exponent to find the human-readable value.

  6. How precision and rounding are applied

    master

    The library provides fine-grained control over how numbers are displayed through two main mechanisms:

    Decimal Rounding

    Rounding is applied using a power-of-10 scaling factor based on the round parameter ($r$): rounded_value = round(value * 10^r) / 10^r

    Significant Digits (Precision)

    If a precision ($p > 0$) is specified, the library adjusts the value to show $p$ significant digits after the rounding step is complete: precise_value = toPrecision(rounded_value, p)

    Scientific Notation Avoidance

    If precision formatting results in scientific notation (containing 'E') for exponents less than 8, the library automatically increments the exponent and recalculates the value to ensure the output remains in standard decimal notation.

  7. Implement functions using filesize design patterns

    master

    Follow these patterns for robust and performant function design:

    • Small, Focused Functions: Ensure functions have a single responsibility.
    • Default Parameters: Use ES6 default parameters for optional arguments.
    • Early Returns: Return early for error conditions to avoid nested logic.
    • Input Validation: Validate all inputs at entry points to ensure security and correctness.
    • Performance Optimization:
      • Use pre-computed lookup tables instead of runtime calculations where possible.
      • Implement fast paths for common cases (e.g., handling zero values).
    // Use default parameters
    export function partial (options = {}) {
    	return arg => filesize(arg, options);
    }
    
    // Use early returns for error handling
    if (typeof arg !== "bigint" && isNaN(arg)) {
    	throw new TypeError(INVALID_NUMBER);
    }
    
    // Use pre-computed values for performance
    export const LOG_2_1024 = Math.log(1024);
  8. How partial application works in filesize

    master

    The partial function allows you to pre-configure certain options of the filesize utility and return a new function that uses those settings. This is useful for creating specialized formatters (e.g., a formatter that always uses a specific locale or specific symbols) without passing the full options object every time.

    To ensure that pre-configured options do not leak side effects between calls, the partial function performs a deep clone of the following option keys:

    • localeOptions
    • symbols
    • fullforms

    Cloning is performed using structuredClone where available, falling back to JSON.parse(JSON.stringify()) in environments that do not support it. This ensures that plain objects, arrays, strings, numbers, booleans, and null are preserved correctly.

  9. Choose between SI, IEC, and JEDEC standards

    master

    The standard option determines which unit system and base are used:

    • "si" (default): Uses base 10 (powers of 1000) with SI symbols (e.g., kB, MB, GB).
    • "iec": Uses base 1024 (powers of 1024) with binary prefixes (e.g., KiB, MiB, GiB).
    • "jedec": Uses base 1024 (powers of 1024) with traditional symbols (e.g., KB, MB, GB).

    Note: When using iec, it is recommended to set base: 2.

  10. Select unit standards (SI, IEC, JEDEC)

    master

    The standard option determines how the base and the unit symbols are calculated.

    • si: Decimal standard (base 10, e.g., kB, MB).
    • iec: Binary standard (base 2, e.g., KiB, MiB).
    • jedec: Binary format using decimal symbols (base 2, but uses KB, MB).

    If base is set to 2 but no standard is provided, the library defaults to the IEC standard.

    import { filesize } from 'filesize';
    
    // IEC binary standard
    filesize(1024, { standard: "iec" }); // "1 KiB"
    
    // JEDEC binary format
    filesize(1024, { standard: "jedec" }); // "1 KB"
    filesize(265318, { standard: "jedec" }); // "259.1 KB"
  11. How filesize handles special input cases

    master

    The library includes specific logic for non-standard or edge-case inputs:

    Zero Input

    When the input is 0, the result is always 0 with an exponent of 0 and the base unit (e.g., "0 B").

    Negative Input

    For negative byte values, the library processes the absolute value and then re-applies the negative sign to the final formatted string: result = -|filesize(|bytes|, options)|

    Overflow Handling

    To prevent values like "1024 KB" from appearing instead of "1 MB", the library checks if a rounded value equals the unit ceiling. If it does, it increments the exponent and resets the value to 1 (provided the exponent is auto-calculated).