### Install filesize.js Source: https://github.com/avoidwork/filesize.js/blob/master/README.md Install the filesize.js package using npm. ```bash npm install filesize ``` -------------------------------- ### Start development mode Source: https://github.com/avoidwork/filesize.js/blob/master/CONTRIBUTING.md Run the project in development mode with hot-reloading. ```bash npm run dev ``` -------------------------------- ### Install dependencies Source: https://github.com/avoidwork/filesize.js/blob/master/CONTRIBUTING.md Install project dependencies using npm. ```bash npm install ``` -------------------------------- ### Filesize Output Format Examples Source: https://github.com/avoidwork/filesize.js/blob/master/docs/TECHNICAL_DOCUMENTATION.md Demonstrates different output formats for file sizes: string (default), array, object, and exponent. ```javascript // String output (default) filesize(1536) // "1.54 kB" ``` ```javascript // Array output filesize(1536, { output: "array" }) // [1.54, "kB"] ``` ```javascript // Object output filesize(1536, { output: "object" }) // { value: 1.54, symbol: "kB", exponent: 1, unit: "kB" } ``` ```javascript // Exponent output filesize(1536, { output: "exponent" }) // 1 ``` -------------------------------- ### Development Commands with npm Source: https://github.com/avoidwork/filesize.js/blob/master/README.md Essential npm commands for managing the development workflow. Includes installing dependencies, starting a development server with live reload, building distributions, and linting the code. ```bash npm install # Install dependencies ``` ```bash npm run dev # Development mode with live reload ``` ```bash npm run build # Build distributions ``` ```bash npm run lint # Check code style ``` ```bash npm run lint:fix # Auto-fix linting issues ``` -------------------------------- ### Code style conventions Source: https://github.com/avoidwork/filesize.js/blob/master/CONTRIBUTING.md Example of JSDoc, naming conventions, and import grouping. ```javascript /** * Description * @param {type} param - Description * @returns {type} Description */ export function functionName(param) { // Implementation } // Constants export const CONSTANT_NAME = 'value'; // Imports: group by source, alphabetize import { ARRAY, BIT, BYTE } from './constants.js'; import { helperFunction } from './helpers.js'; ``` -------------------------------- ### Install Filesize.js with npm Source: https://github.com/avoidwork/filesize.js/wiki/Home Use npm to install the filesize.js package. This is the standard way to add the library to your Node.js project. ```bash $ npm install filesize ``` -------------------------------- ### Test Suite Setup with Node:test Source: https://github.com/avoidwork/filesize.js/blob/master/docs/CODE_STYLE_GUIDE.md Set up tests using the built-in 'node:test' module and 'node:assert' for assertions. Ensure all necessary modules are imported. ```javascript import assert from "node:assert"; import { describe, it } from "node:test"; import { filesize } from "../../src/filesize.js"; describe("filesize()", () => { it("should convert bytes to human readable format", () => { const result = filesize(1024); assert.strictEqual(result, "1.02 kB"); }); }); ``` -------------------------------- ### Filesize.js Basic and Custom Examples Source: https://github.com/avoidwork/filesize.js/wiki/Home Demonstrates basic usage of the filesize function and its customization options like `bits`, `base`, and `round`. The `bits: true` option enables bit sizes, while `base` changes the numerical base for calculation. ```javascript filesize(500); // "500 B" filesize(500, {bits: true}); // "4.00 kb" filesize(265318); // "265.32 kB" filesize(265318, {base: 2}); // "259.10 kB" filesize(265318, {base: 2, round: 1}); // "259.1 kB" ``` -------------------------------- ### Default Conversion Example (1536 bytes) Source: https://github.com/avoidwork/filesize.js/blob/master/docs/TECHNICAL_DOCUMENTATION.md Demonstrates the default conversion process using decimal (JEDEC) standard for 1536 bytes. It includes exponent calculation, divisor lookup, value calculation, and rounding. ```text Given: bytes = 1536, default settings (decimal, JEDEC standard) 1. Calculate exponent: e = floor(ln(1536)/ln(1000)) = floor(1.062) = 1 2. Lookup divisor: DECIMAL_POWERS[1] = 1000 3. Calculate value: value = 1536 / 1000 = 1.536 4. Apply rounding (2 decimal places): 1.536 -> 1.54 5. Result: "1.54 KB" ``` -------------------------------- ### JSDoc Template Example Source: https://github.com/avoidwork/filesize.js/blob/master/AGENTS.md A standard JSDoc template demonstrating parameter, return, and exception documentation, along with an example usage. ```javascript /** * Function description * @param {type} paramName - Parameter description * @param {type} [paramName=default] - Optional parameter * @returns {type} Return description * @throws {ErrorType} When condition occurs * @example * // Example usage * functionName(arg); // "result" */ ``` -------------------------------- ### Conventional Commits examples Source: https://github.com/avoidwork/filesize.js/blob/master/CONTRIBUTING.md Examples of commit messages following the Conventional Commits format. ```text feat: add precision option for significant digits fix: correct bits auto-increment with forced exponent docs: update README with TypeScript examples refactor: simplify exponent auto-detection logic build: update rollup configuration test: add coverage for NaN exponent edge case ``` -------------------------------- ### Create Pre-configured Formatters with partial() Source: https://github.com/avoidwork/filesize.js/blob/master/AGENTS.md Use the `partial` function to create reusable formatters with predefined options. This example shows how to create formatters for binary IEC units, bits, and precise decimal places. ```javascript import { partial } from 'filesize'; const formatBinary = partial({base: 2, standard: "iec"}); const formatBits = partial({bits: true}); const formatPrecise = partial({round: 3, pad: true}); ``` -------------------------------- ### Binary Conversion Example (1536 bytes) Source: https://github.com/avoidwork/filesize.js/blob/master/docs/TECHNICAL_DOCUMENTATION.md Illustrates the conversion process using the binary (IEC) standard for 1536 bytes. It shows the calculation of the exponent using base 1024 and the resulting value. ```text Given: bytes = 1536, base = 2 (IEC standard) 1. Calculate exponent: e = floor(ln(1536)/ln(1024)) = floor(1.084) = 1 2. Lookup divisor: BINARY_POWERS[1] = 1024 3. Calculate value: value = 1536 / 1024 = 1.5 4. Result: "1.5 KiB" ``` -------------------------------- ### Write unit tests Source: https://github.com/avoidwork/filesize.js/blob/master/CONTRIBUTING.md Example of writing a unit test using Node.js built-in test runner and assert module. ```javascript import assert from 'node:assert'; import { describe, it } from 'node:test'; import { filesize } from '../../src/filesize.js'; describe('Feature', () => { it('should do something', () => { const result = filesize(1024); assert.strictEqual(result, '1.02 kB'); }); }); ``` -------------------------------- ### Input Validation Example Source: https://github.com/avoidwork/filesize.js/blob/master/docs/CODE_STYLE_GUIDE.md Implement robust input validation at entry points to prevent unexpected behavior. This example checks for non-bigint and non-NaN numeric types. ```javascript if (typeof arg !== "bigint" && isNaN(arg)) { throw new TypeError(INVALID_NUMBER); } ``` -------------------------------- ### Input Types Source: https://github.com/avoidwork/filesize.js/blob/master/docs/API.md Shows examples of using different number types as input. ```APIDOC ## Input Types ### Number ```javascript filesize(1024) // "1.02 kB" filesize(1536.5) // "1.54 kB" filesize(-1024) // "-1.02 kB" ``` ``` -------------------------------- ### Cloud Storage Dashboard Component Source: https://github.com/avoidwork/filesize.js/blob/master/docs/TECHNICAL_DOCUMENTATION.md Example React component demonstrating how to use `filesize` and `partial` to display cloud storage usage and quota, incorporating locale and object output for programmatic use. ```javascript // components/StorageWidget.js import { filesize, partial } from 'filesize'; import { useLocale } from '@/hooks/useLocale'; const formatStorage = partial({ standard: "iec", round: 1, output: "object" }); function StorageWidget({ usage, quota }) { const { locale } = useLocale(); const usageFormatted = filesize(usage, { locale, standard: "iec", localeOptions: { notation: "compact" } }); const quotaFormatted = filesize(quota, { locale, standard: "iec" }); const percentage = (usage / quota) * 100; return (

{usageFormatted} of {quotaFormatted} used

); } ``` -------------------------------- ### SI Unit Standard Example Source: https://github.com/avoidwork/filesize.js/blob/master/docs/API.md Demonstrates the default SI (International System of Units) standard, which uses base 10 (powers of 1000) and standard SI symbols (kB, MB, GB). ```javascript filesize(1000) // "1 kB" filesize(1000000) // "1 MB" filesize(1000000000) // "1 GB" ``` -------------------------------- ### Conventional Commit Message Examples Source: https://github.com/avoidwork/filesize.js/blob/master/AGENTS.md Examples of commit messages following the Conventional Commits specification for various types of changes. ```git feat: add new output format option fix: correct rounding on negative pad values docs: update AGENTS.md with new patterns test: add coverage for bits auto-increment chore: update rollup config ``` -------------------------------- ### JavaScript Early Return for Error Conditions Source: https://github.com/avoidwork/filesize.js/blob/master/docs/CODE_STYLE_GUIDE.md Implement early returns for error conditions to simplify control flow and improve readability. This example checks for invalid input types. ```javascript if (typeof arg !== "bigint" && isNaN(arg)) { throw new TypeError(INVALID_NUMBER); } if (typeof roundingFunc !== FUNCTION) { throw new TypeError(INVALID_ROUND); } ``` -------------------------------- ### Build the project Source: https://github.com/avoidwork/filesize.js/blob/master/CONTRIBUTING.md Compile and build the project after making changes. ```bash npm run build ``` -------------------------------- ### Build project distributions Source: https://github.com/avoidwork/filesize.js/blob/master/CONTRIBUTING.md Build all project distributions, enable watch mode for development, or analyze bundle sizes. ```bash npm run build ``` ```bash npm run build:watch ``` ```bash npm run build:analyze ``` -------------------------------- ### Run All Benchmarks Source: https://github.com/avoidwork/filesize.js/blob/master/benchmarks/README.md Execute all benchmark suites in the 'benchmarks' directory. Ensure you are in the 'benchmarks' directory before running. ```bash cd benchmarks node index.js ``` -------------------------------- ### Basic Usage Source: https://github.com/avoidwork/filesize.js/blob/master/README.md Shows how to use the filesize function with default and custom options for byte conversion. ```javascript import {filesize, partial} from "filesize"; filesize(1024); // "1.02 kB" filesize(265318); // "265.32 kB" filesize(1024, {standard: "iec"}); // "1 KiB" filesize(1024, {bits: true}); // "8.19 kbit" ``` -------------------------------- ### Build Commands Source: https://github.com/avoidwork/filesize.js/blob/master/AGENTS.md Commands for building the project distributions, development mode, and bundle analysis. ```bash npm run build # Build all distributions npm run dev # Development mode with live reload npm run build:watch # Watch mode npm run build:analyze # Bundle size analysis ``` -------------------------------- ### Custom Unit Symbols Source: https://github.com/avoidwork/filesize.js/blob/master/README.md Allows overriding default unit symbols with custom ones, for example, using Cyrillic 'Б' for Bytes. ```javascript // Custom symbols ilesize(1, {symbols: {B: "Б"}}); // "1 Б" ``` -------------------------------- ### JavaScript Function with Destructuring and Default Parameters Source: https://github.com/avoidwork/filesize.js/blob/master/docs/CODE_STYLE_GUIDE.md Use tabs for indentation in JavaScript. This example shows a function definition with destructured parameters and default values. ```javascript export function filesize (arg, { bits = false, pad = false } = {}) { const result = []; return result; } ``` -------------------------------- ### Project File and Directory Structure Source: https://github.com/avoidwork/filesize.js/blob/master/docs/CODE_STYLE_GUIDE.md Use kebab-case for file and directory names. The project uses simple descriptive names for clarity. ```plaintext src/ ├── constants.js ├── filesize.js └── helpers.js tests/ └── unit/ ├── filesize-helpers.test.js └── filesize.test.js ``` -------------------------------- ### JSDoc for Exported JavaScript Function Source: https://github.com/avoidwork/filesize.js/blob/master/docs/CODE_STYLE_GUIDE.md All exported functions must have JSDoc comments detailing parameters, return types, and potential errors. Includes an example usage. ```javascript /** * Converts a file size in bytes to a human-readable string * @param {number|string|bigint} arg - The file size in bytes * @param {Object} [options={}] - Configuration options * @param {boolean} [options.bits=false] - Calculate bits instead of bytes * @param {number} [options.round=2] - Decimal places to round to * @returns {string|Array|Object|number} Formatted file size * @throws {TypeError} When arg is not a valid number * @example * filesize(1024) // "1.02 kB" */ export function filesize (arg, options = {}) { // Implementation } ``` -------------------------------- ### Testing Commands Source: https://github.com/avoidwork/filesize.js/blob/master/docs/CODE_STYLE_GUIDE.md Run the test suite with npm scripts. 'npm test' executes the full suite including linting and node:test, while 'npm run test:watch' enables live test watching. ```bash npm test # Full test suite (lint + node:test) npm run test:watch # Live test watching ``` -------------------------------- ### Forced Exponent Behavior Examples Source: https://github.com/avoidwork/filesize.js/blob/master/AGENTS.md Demonstrates how explicitly setting the `exponent` option disables auto-increment and scientific notation normalization. This ensures the output uses the specified exponent regardless of the input value. ```javascript filesize(1024, { exponent: 0, bits: true }); // "8192 bit" (not auto-incremented to kbit) filesize(1024, { exponent: 0 }); // "1024 B" (not auto-incremented to kB) ``` -------------------------------- ### Clone the repository Source: https://github.com/avoidwork/filesize.js/blob/master/CONTRIBUTING.md Clone your forked repository and navigate into the project directory. ```bash git clone https://github.com/your-username/filesize.js.git cd filesize.js ``` -------------------------------- ### Run Tests with npm Source: https://github.com/avoidwork/filesize.js/blob/master/README.md Use these npm commands to execute the test suite. 'npm test' runs all tests, while 'npm run test:watch' enables live test watching for continuous feedback during development. ```bash npm test # Run all tests (lint + node:test) ``` ```bash npm run test:watch # Live test watching ``` -------------------------------- ### Project Layout Structure Source: https://github.com/avoidwork/filesize.js/blob/master/AGENTS.md Illustrates the expected directory structure for the filesize.js project, including source, tests, build outputs, and documentation. ```text filesize.js/ ├── src/ │ ├── filesize.js # Main implementation (filesize + partial) │ ├── helpers.js # Helper functions (5 exported functions) │ └── constants.js # Constants, symbols, lookup tables ├── tests/ │ └── unit/ │ ├── filesize-helpers.test.js # Helper function tests │ └── filesize.test.js # Main function tests ├── dist/ # Built distributions (generated) ├── types/ # TypeScript definitions └── docs/ # Documentation ``` -------------------------------- ### Default String Output Source: https://github.com/avoidwork/filesize.js/blob/master/docs/API.md The default output format is a string, combining the numerical value and its unit, separated by a space or a custom spacer. Examples show default, custom separator, and custom spacer. ```javascript filesize(1536) // "1.54 kB" filesize(265318, {separator: ","}) // "265,32 kB" filesize(265318, {spacer: ""}) // "265.32kB" ``` -------------------------------- ### Functional Programming with Filesize Partial Source: https://github.com/avoidwork/filesize.js/blob/master/docs/TECHNICAL_DOCUMENTATION.md Demonstrates creating specialized file size formatters using the `partial` function for functional programming patterns. Requires importing `partial`. ```javascript import { partial } from 'filesize'; // Create specialized formatters const formatBinary = partial({ standard: "iec", round: 1 }); const formatPrecise = partial({ round: 4, pad: true }); formatBinary(1024); // "1 KiB" formatPrecise(1536); // "1.5360 kB" ``` -------------------------------- ### Utilize BigInt for Large Number Support Source: https://github.com/avoidwork/filesize.js/blob/master/AGENTS.md The filesize.js library supports BigInt for handling arbitrarily large numbers. Examples demonstrate formatting both standard BigInt inputs and string representations of very large numbers. ```javascript filesize(BigInt(1024)); // "1.02 kB" filesize(BigInt("10000000000000000000")); // Works with huge numbers ``` -------------------------------- ### TypeScript Usage Source: https://github.com/avoidwork/filesize.js/blob/master/README.md Demonstrates basic and advanced TypeScript usage with filesize.js, including type definitions for results and partial application. ```typescript import { filesize, partial } from 'filesize'; const result: string = filesize(1024); const formatted: { value: number; symbol: string; exponent: number; unit: string } = filesize(1024, { output: 'object' }); const formatter: (arg: number | bigint) => string = partial({ standard: 'iec' }); ``` -------------------------------- ### partial(options) Source: https://github.com/avoidwork/filesize.js/blob/master/docs/TECHNICAL_DOCUMENTATION.md Creates a new function with pre-configured options. This is useful for creating specialized versions of the filesize function that consistently use specific settings, like a fixed base or precision. ```APIDOC ## partial(options) ### Description Creates a partially applied function with preset options. ### Parameters - `options` (Object): Default configuration ### Returns Function ``` -------------------------------- ### Run tests Source: https://github.com/avoidwork/filesize.js/blob/master/CONTRIBUTING.md Execute all tests, including linting and Node.js built-in tests, or use live test watching. ```bash npm test ``` ```bash npm run test:watch ``` -------------------------------- ### partial(options) Source: https://github.com/avoidwork/filesize.js/blob/master/docs/API.md Creates a partially applied version of filesize with preset options, allowing for reusable formatting configurations. ```APIDOC ## partial(options) ### Description Creates a partially applied version of filesize with preset options. ### Parameters #### Parameters - **options** (Object) - Optional - Default: `{}` - Configuration options (same as filesize). ### Returns (Function) - A function that takes a file size and returns formatted output. ### Examples ```javascript import {partial} from "filesize"; // Create specialized formatters const formatBinary = partial({base: 2, standard: "iec"}); const formatBits = partial({bits: true}); const formatPrecise = partial({round: 3, pad: true}); const formatGerman = partial({locale: "de"}); // Use throughout application formatBinary(1024) // "1 KiB" formatBinary(1048576) // "1 MiB" formatBits(1024) // "8.19 kbit" formatPrecise(1536) // "1.536 kB" formatGerman(265318) // "265,32 kB" // Method chaining const sizes = [1024, 2048, 4096]; sizes.map(formatBinary) // ["1 KiB", "2 KiB", "4 KiB"] ``` ``` -------------------------------- ### Basic Filesize Conversions Source: https://github.com/avoidwork/filesize.js/blob/master/docs/TECHNICAL_DOCUMENTATION.md Shows simple file size conversions using the default settings. Ensure the 'filesize' function is imported. ```javascript import { filesize } from 'filesize'; // Simple conversion ilesize(1024); // "1.02 kB" ilesize(1536); // "1.54 kB" ilesize(1073741824); // "1.07 GB" ``` -------------------------------- ### Advanced Locale Configuration with Custom Options Source: https://github.com/avoidwork/filesize.js/blob/master/docs/TECHNICAL_DOCUMENTATION.md Demonstrates advanced locale configuration using custom locale options for different regions. Includes a class for context-aware formatting and applying specific configurations based on region or context. ```javascript // Custom locale options for different regions const regionConfigs = { europe: { locale: 'en-GB', standard: 'iec', localeOptions: { minimumFractionDigits: 1, maximumFractionDigits: 2 } }, asia: { locale: 'ja-JP', standard: 'iec', localeOptions: { notation: 'compact', compactDisplay: 'short' } }, americas: { locale: 'en-US', standard: 'jedec', localeOptions: { style: 'decimal' } } }; // Context-aware formatting class LocalizedFileSize { constructor(region = 'americas') { this.config = regionConfigs[region]; this.formatter = partial(this.config); } format(bytes) { return this.formatter(bytes); } formatWithContext(bytes, context = 'storage') { const contextOptions = { storage: { standard: 'iec' }, network: { bits: true, standard: 'si' }, memory: { standard: 'iec', round: 0 } }; return filesize(bytes, { ...this.config, ...contextOptions[context] }); } } ``` -------------------------------- ### Run Individual Benchmarks Source: https://github.com/avoidwork/filesize.js/blob/master/benchmarks/README.md Execute specific benchmark suites by their respective filenames. This allows for focused performance analysis. ```bash # Basic performance tests node basic-performance.js ``` ```bash # Options impact analysis node options-benchmark.js ``` ```bash # Stress testing node stress-test.js ``` ```bash # Partial function analysis node partial-benchmark.js ``` -------------------------------- ### Mermaid Standard Selection Logic Diagram Source: https://github.com/avoidwork/filesize.js/blob/master/docs/TECHNICAL_DOCUMENTATION.md Illustrates the logic for selecting the appropriate standard (SI, IEC, JEDEC) based on input parameters like 'standard' and 'base', including cached configurations and default fallbacks. ```mermaid flowchart TD Input[Input: standard, base] --> CheckCached{Standard in
cached configs?} CheckCached -->|Yes: SI| ReturnSI[isDecimal: true
ceil: 1000
actualStandard: JEDEC] CheckCached -->|Yes: IEC| ReturnIEC[isDecimal: false
ceil: 1024
actualStandard: IEC] CheckCached -->|Yes: JEDEC| ReturnJEDEC[isDecimal: false
ceil: 1024
actualStandard: JEDEC] CheckCached -->|No| CheckBase{Base = 2?} CheckBase -->|Yes| ReturnBase2[isDecimal: false
ceil: 1024
actualStandard: IEC] CheckBase -->|No| ReturnDefault[isDecimal: true
ceil: 1000
actualStandard: JEDEC] ReturnSI --> Result[Final Configuration] ReturnIEC --> Result ReturnJEDEC --> Result ReturnBase2 --> Result ReturnDefault --> Result style Input fill:#166534,stroke:#15803d,stroke-width:2px,color:#ffffff style Result fill:#1e40af,stroke:#1e3a8a,stroke-width:2px,color:#ffffff style CheckCached fill:#7c2d12,stroke:#92400e,stroke-width:2px,color:#ffffff ``` -------------------------------- ### Data Flow in filesize.js Source: https://github.com/avoidwork/filesize.js/blob/master/AGENTS.md Outlines the sequential steps involved in the data processing pipeline for the filesize.js utility, from input to output generation. ```text Input → Validation → Standard Normalization → Exponent Calculation → Value Conversion → Formatting → Output Generation ``` -------------------------------- ### Partial Application for Reusable Formatters Source: https://github.com/avoidwork/filesize.js/blob/master/README.md Illustrates creating reusable formatters using the partial application feature for specific standards like IEC. ```javascript import {partial} from "filesize"; const formatBinary = partial({standard: "iec"}); formatBinary(1024); // "1 KiB" formatBinary(1048576); // "1 MiB" ``` -------------------------------- ### Building Commands Source: https://github.com/avoidwork/filesize.js/blob/master/docs/CODE_STYLE_GUIDE.md Manage project builds using npm scripts. 'npm run build' compiles all distributions, 'npm run build:watch' enables watch mode, and 'npm run build:analyze' performs bundle size analysis. ```bash npm run build # Build all distributions npm run build:watch # Watch mode npm run build:analyze # Bundle size analysis ``` -------------------------------- ### Run Custom Benchmark with filesize.js Source: https://github.com/avoidwork/filesize.js/blob/master/benchmarks/README.md Use this function to benchmark custom usage patterns of the filesize library. Ensure you have the library imported and define your test function with specific options. ```javascript import { filesize } from "../dist/filesize.js"; const ITERATIONS = 10000; function benchmark(testName, testFunction, iterations = ITERATIONS) { // Warmup for (let i = 0; i < 1000; i++) { testFunction(); } const startTime = process.hrtime.bigint(); for (let i = 0; i < iterations; i++) { testFunction(); } const endTime = process.hrtime.bigint(); const totalTime = Number(endTime - startTime) / 1000000; const avgTime = totalTime / iterations; const opsPerSecond = Math.round(1000 / avgTime); return { testName, opsPerSecond, avgTime }; } // Your custom test const result = benchmark("Custom test", () => { return filesize(1024 * 1024, { /* your options */ }); }); console.log(result); ``` -------------------------------- ### Create Specialized Filesize Formatters with `partial` Source: https://github.com/avoidwork/filesize.js/blob/master/docs/API.md The `partial` function creates a new function with preset options, allowing for reusable, specialized file size formatters. Import `partial` from the library. ```javascript import {partial} from "filesize"; // Create specialized formatters const formatBinary = partial({base: 2, standard: "iec"}); const formatBits = partial({bits: true}); const formatPrecise = partial({round: 3, pad: true}); const formatGerman = partial({locale: "de"}); // Use throughout application formatBinary(1024) // "1 KiB" formatBinary(1048576) // "1 MiB" formatBits(1024) // "8.19 kbit" formatPrecise(1536) // "1.536 kB" formatGerman(265318) // "265,32 kB" // Method chaining const sizes = [1024, 2048, 4096]; sizes.map(formatBinary) // ["1 KiB", "2 KiB", "4 KiB"] ``` -------------------------------- ### Advanced Filesize Configuration Source: https://github.com/avoidwork/filesize.js/blob/master/docs/TECHNICAL_DOCUMENTATION.md Illustrates advanced configuration options for filesize, including different standards (IEC, JEDEC), high precision, bit conversion, and object output. ```javascript // IEC binary standard ilesize(1024, { standard: "iec" }); // "1 KiB" ``` ```javascript // JEDEC binary format (KB, MB, GB with binary calculation) ilesize(1024, { standard: "jedec" }); // "1 KB" ilesize(265318, { standard: "jedec" }); // "259.1 KB" ``` ```javascript // High precision ilesize(1536, { round: 3 }); // "1.536 kB" ``` ```javascript // Bits instead of bytes ilesize(1024, { bits: true }); // "8.19 kbit" ``` ```javascript // Object output for programmatic use ilesize(1536, { output: "object" }); // { value: 1.54, symbol: "kB", exponent: 1, unit: "kB" } ``` -------------------------------- ### Test Commands Source: https://github.com/avoidwork/filesize.js/blob/master/AGENTS.md Commands for running the test suite, including full testing with coverage and live test watching. ```bash npm test # Full test suite (lint + node:test with coverage) npm run test:watch # Live test watching ``` -------------------------------- ### Push to origin Source: https://github.com/avoidwork/filesize.js/blob/master/CONTRIBUTING.md Push your feature branch to your remote fork. ```bash git push origin feature/your-feature-name ``` -------------------------------- ### Mermaid System Architecture Diagram Source: https://github.com/avoidwork/filesize.js/blob/master/docs/TECHNICAL_DOCUMENTATION.md Visual representation of the filesize library's module structure, showing core components and external dependencies. ```mermaid graph LR subgraph "filesize Library" A[constants.js
Constants & Symbols] B[filesize.js
Orchestrator
17 LOC pipeline] C[helpers.js
10 Delegate Functions] D[Types
TypeScript Definitions] end subgraph "External Dependencies" E[Math Object
Rounding Functions] F[Intl API
Localization] end A --> B A --> C B --> C B --> E B --> F C --> E C --> F style A fill:#d97706,stroke:#b45309,stroke-width:2px,color:#ffffff style B fill:#166534,stroke:#15803d,stroke-width:2px,color:#ffffff style C fill:#1e40af,stroke:#15803d,stroke-width:2px,color:#ffffff style D fill:#7c2d12,stroke:#92400e,stroke-width:2px,color:#ffffff ``` -------------------------------- ### IEC Standard Usage Source: https://github.com/avoidwork/filesize.js/blob/master/docs/API.md Demonstrates how to use the IEC standard (base 1024 with binary prefixes like KiB, MiB, GiB). ```APIDOC ## IEC (International Electrotechnical Commission) Uses base 1024 (powers of 1024) with binary prefixes (KiB, MiB, GiB). ```javascript filesize(1024, {base: 2, standard: "iec"}) // "1 KiB" filesize(1048576, {base: 2, standard: "iec"}) // "1 MiB" filesize(1073741824, {base: 2, standard: "iec"}) // "1 GiB" ``` ``` -------------------------------- ### Virtualized Filesize Formatter with Cache Source: https://github.com/avoidwork/filesize.js/blob/master/docs/TECHNICAL_DOCUMENTATION.md Optimizes performance for large datasets by using a virtual scrolling approach with memoization. It caches formatted sizes to avoid redundant calculations. ```javascript // Problem: Formatting thousands of file sizes is slow // Solution: Virtual scrolling with memoization class VirtualizedFileSizeFormatter { constructor(options = {}) { this.formatter = partial(options); this.cache = new Map(); this.maxCacheSize = 1000; } format(bytes) { if (this.cache.has(bytes)) { return this.cache.get(bytes); } const result = this.formatter(bytes); if (this.cache.size >= this.maxCacheSize) { const firstKey = this.cache.keys().next().value; this.cache.delete(firstKey); } this.cache.set(bytes, result); return result; } batchFormat(bytesArray) { return bytesArray.map(bytes => this.format(bytes)); } } ``` -------------------------------- ### JEDEC Standard Usage Source: https://github.com/avoidwork/filesize.js/blob/master/docs/API.md Demonstrates how to use the JEDEC standard (base 1024 with traditional symbols like KB, MB, GB). ```APIDOC ## JEDEC Uses base 1024 (powers of 1024) with traditional symbols (KB, MB, GB). ```javascript filesize(1024, {standard: "jedec"}) // "1 KB" filesize(1048576, {standard: "jedec"}) // "1 MB" filesize(265318, {standard: "jedec"}) // "259.1 KB" ``` ``` -------------------------------- ### Run tests Source: https://github.com/avoidwork/filesize.js/blob/master/CONTRIBUTING.md Execute all project tests to ensure changes do not introduce regressions. ```bash npm test ``` -------------------------------- ### filesize(arg, options) Source: https://github.com/avoidwork/filesize.js/blob/master/docs/TECHNICAL_DOCUMENTATION.md Converts a given number of bytes into a human-readable string format. It supports various options to customize the output, such as the base for conversion (SI or binary) and the precision of the result. ```APIDOC ## filesize(arg, options) ### Description Converts bytes to human-readable format. ### Parameters - `arg` (number|bigint): File size in bytes - `options` (Object): Configuration options ### Returns string|Array|Object|number ``` -------------------------------- ### Mermaid System Architecture Diagram Source: https://github.com/avoidwork/filesize.js/blob/master/docs/TECHNICAL_DOCUMENTATION.md Visual representation of the filesize library's core components and configuration layer, illustrating the data flow. ```mermaid graph TB subgraph "Core Components" A[Input Validation] --> B[Standard Normalization] B --> C[Exponent Calculation] C --> D[Value Conversion] D --> E[Formatting Engine] E --> F[Output Generation] end subgraph "Configuration Layer" G[Constants Module] H[Standards Config] I[Locale Settings] J[Symbol Mappings] end subgraph "Public API" K[filesize Function] L[partial Function] end G --> A H --> B I --> E J --> E K --> A L --> K style A fill:#1e40af,stroke:#1e3a8a,stroke-width:2px,color:#ffffff style E fill:#7c2d12,stroke:#92400e,stroke-width:2px,color:#ffffff style K fill:#166534,stroke:#15803d,stroke-width:2px,color:#ffffff ``` -------------------------------- ### filesize(arg, options) Source: https://github.com/avoidwork/filesize.js/blob/master/AGENTS.md The main orchestrator function that delegates validation, calculation, rounding, formatting, and output dispatch for file sizes. ```APIDOC ## filesize(arg, options) ### Description Orchestrates the entire file size formatting process, including validation, exponent calculation, value conversion, rounding, number formatting, and output dispatch. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **arg** (number | string | BigInt): The file size value to format. - **options** (object) - Optional - Configuration options for formatting. See API Reference section 5.1 for details. ### Request Example ```javascript import filesize from 'filesize'; filesize(1024); // "1.02 KB" filesize(2048, { bits: true, output: "array" }); // [2, "KiB"] ``` ### Response #### Success Response (200) - **string**: Formatted file size string (default). - **array**: Array containing the value and unit (e.g., `[1.5, "KB"]`). - **object**: Object with detailed formatting information (e.g., `{value: 1.5, symbol: "KB", exponent: 1, unit: "KB"}`). - **exponent**: The calculated exponent for the size. #### Response Example ```json { "example": "1.5 KB" } ``` ```json { "example": "[1.5, \"KB\"]" } ``` ```json { "example": "{ \"value\": 1.5, \"symbol\": \"KB\", \"exponent\": 1, \"unit\": \"KB\" }" } ``` ```json { "example": "1" } ``` ``` -------------------------------- ### Format code Source: https://github.com/avoidwork/filesize.js/blob/master/CONTRIBUTING.md Format code using oxfmt. ```bash npm run format:fix ``` -------------------------------- ### partial(options) Source: https://github.com/avoidwork/filesize.js/blob/master/AGENTS.md Creates a pre-configured formatter function with immutable options, allowing for consistent formatting across multiple calls. ```APIDOC ## partial(options) ### Description Creates a pre-configured formatter function with immutable options. This is useful for setting up consistent formatting rules (like using IEC standard or specific precision) that can be reused. ### Method `partial(options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (object): Configuration options to be frozen and used by the returned formatter function. See API Reference section 5.1 for details. ### Returns - **function**: A formatter function that accepts a single argument (the file size value) and returns the formatted string based on the pre-configured options. ### Request Example ```javascript import { partial } from 'filesize'; const formatBinary = partial({base: 2, standard: "iec"}); const formatBits = partial({bits: true}); const formatPrecise = partial({round: 3, pad: true}); console.log(formatBinary(1024)); // "1 KiB" console.log(formatBits(8192)); // "8192 bit" console.log(formatPrecise(1234.5678)); // "1.235" ``` ### Response #### Success Response (200) - **function**: A pre-configured file size formatter. #### Response Example ```json { "example": "[Function: formatBinary]" } ``` ``` -------------------------------- ### Set Output Format Source: https://github.com/avoidwork/filesize.js/blob/master/docs/API.md Determines the output format: 'string', 'array', 'object', or 'exponent'. Default is 'string'. ```javascript filesize(1536, {output: "string"}) // "1.54 kB" ``` ```javascript filesize(1536, {output: "array"}) // [1.54, "kB"] ``` ```javascript filesize(1536, {output: "object"}) // {value: 1.54, symbol: "kB", exponent: 1, unit: "kB"} ``` ```javascript filesize(1536, {output: "exponent"}) // 1 ``` -------------------------------- ### Load and Use Filesize.js with AMD Source: https://github.com/avoidwork/filesize.js/wiki/Home Use an AMD loader to require the filesize module. This is suitable for environments that support the Asynchronous Module Definition pattern. ```javascript require("filesize", function (filesize) { // use internally or set on window alert(filesize(1234)); }); ``` -------------------------------- ### Filesize Conversion with Binary Standard (IEC) Source: https://github.com/avoidwork/filesize.js/blob/master/docs/API.md Uses the IEC (International Electrotechnical Commission) standard for binary prefixes (KiB, MiB, etc.) by setting `base` to 2 and `standard` to 'iec'. ```javascript filesize(1024, {base: 2, standard: "iec"}) // "1 KiB" ``` -------------------------------- ### Fast Path Optimization for Zero Source: https://github.com/avoidwork/filesize.js/blob/master/docs/CODE_STYLE_GUIDE.md Implement fast paths for common or trivial cases, such as handling the number zero directly to avoid unnecessary computations. ```javascript // Fast path for zero if (num === 0) { return handleZeroValue(precision, actualStandard, bits, symbols, full, fullforms, output, spacer); } ``` -------------------------------- ### Include Filesize.js via Script Tag Source: https://github.com/avoidwork/filesize.js/wiki/Home Include the filesize.js library using a script tag, typically from a CDN. The `filesize` function will be available globally. ```html ``` -------------------------------- ### Filesize Conversion with Bits Option Source: https://github.com/avoidwork/filesize.js/blob/master/docs/API.md Calculates file size in bits instead of bytes by setting the `bits` option to true. ```javascript filesize(1024, {bits: true}) // "8.19 kbit" ``` -------------------------------- ### Output Formats Source: https://github.com/avoidwork/filesize.js/blob/master/docs/API.md Details the different output formats available for the filesize function: string, array, object, and exponent. ```APIDOC ## Output Formats ### String Output (default) Returns a formatted string with value and unit separated by a space (or custom spacer). ```javascript filesize(1536) // "1.54 kB" filesize(265318, {separator: ","}) // "265,32 kB" filesize(265318, {spacer: ""}) // "265.32kB" ``` ### Array Output Returns an array with `[value, symbol]`. ```javascript filesize(1536, {output: "array"}) // [1.54, "kB"] filesize(1024, {output: "array", base: 2}) // [1, "KiB"] ``` ### Object Output Returns an object with `value`, `symbol`, `exponent`, and `unit` properties. ```javascript filesize(1536, {output: "object"}) // {value: 1.54, symbol: "kB", exponent: 1, unit: "kB"} ``` ### Exponent Output Returns the exponent as a number (0 = bytes, 1 = kB/KiB, 2 = MB/MiB, etc.). ```javascript filesize(1536, {output: "exponent"}) // 1 filesize(1048576, {output: "exponent", base: 2}) // 2 ``` ``` -------------------------------- ### Load and Use Filesize.js in Node.js Source: https://github.com/avoidwork/filesize.js/wiki/Home Require the filesize module in your Node.js application and use it to format file sizes. The `unix: true` option formats the output similar to `ls -lh`. ```javascript var filesize = require("filesize"), util = require("util"); util.puts(filesize(1234, {unix: true})); // "1.2K" ``` -------------------------------- ### String Output Format Source: https://github.com/avoidwork/filesize.js/blob/master/README.md Default output format for filesize.js, returning a human-readable string representation of the file size. ```javascript // String (default) filesize(1536); // "1.54 kB" ``` -------------------------------- ### Use Full Unit Names Source: https://github.com/avoidwork/filesize.js/blob/master/README.md Displays the full names of units (e.g., 'kilobytes' instead of 'kB') using the `fullform: true` option. ```javascript // Full form ilesize(1024, {fullform: true}); // "1.02 kilobytes" ilesize(1024, {base: 2, fullform: true}); // "1 kibibyte" ``` -------------------------------- ### filesize(arg, options) Source: https://github.com/avoidwork/filesize.js/blob/master/docs/API.md Converts a file size in bytes to a human-readable string with appropriate units. It supports various options for customization, including bits, rounding, locale, and output format. ```APIDOC ## filesize(arg, options) ### Description Converts a file size in bytes to a human-readable string with appropriate units. ### Parameters #### Parameters - **arg** (number | string | bigint) - Required - The file size in bytes to convert. - **options** (Object) - Optional - Configuration options for formatting. #### Options - **bits** (boolean) - Optional - Default: `false` - If true, calculates bits instead of bytes. - **pad** (boolean) - Optional - Default: `false` - If true, pads decimal places to match round parameter. - **base** (number) - Optional - Default: `-1` - Number base (2 for binary, 10 for decimal, -1 for auto). - **round** (number) - Optional - Default: `2` - Number of decimal places to round to. - **locale** (string | boolean) - Optional - Default: `""` - Locale for number formatting, true for system locale. - **localeOptions** (Object) - Optional - Default: `{}` - Additional options for locale formatting. - **separator** (string) - Optional - Default: `""` - Custom decimal separator. - **spacer** (string) - Optional - Default: `" "` - String to separate value and unit. - **symbols** (Object) - Optional - Default: `{}` - Custom unit symbols. - **standard** (string) - Optional - Default: `""` - Unit standard to use (`si`, `iec`, `jedec`). - **output** (string) - Optional - Default: `"string"` - Output format (`string`, `array`, `object`, `exponent`). - **fullform** (boolean) - Optional - Default: `false` - If true, uses full unit names instead of abbreviations. - **fullforms** (Array) - Optional - Default: `[]` - Custom full unit names. - **exponent** (number) - Optional - Default: `-1` - Force specific exponent (-1 for auto). - **roundingMethod** (string) - Optional - Default: `"round"` - Math rounding method to use (`round`, `floor`, `ceil`). - **precision** (number) - Optional - Default: `0` - Number of significant digits (0 for auto). ### Returns (string | Array | Object | number) - Formatted file size based on output option. ### Throws TypeError - When arg is not a valid number or roundingMethod is invalid. ### Examples ```javascript // Basic usage filesize(1024) // "1.02 kB" filesize(265318) // "265.32 kB" // Bits instead of bytes filesize(1024, {bits: true}) // "8.19 kbit" // Object output filesize(1024, {output: "object"}) // {value: 1.02, symbol: "kB", exponent: 1, unit: "kB"} // Binary standard (IEC) filesize(1024, {base: 2, standard: "iec"}) // "1 KiB" // Full form names filesize(1024, {fullform: true}) // "1.02 kilobytes" // Custom formatting filesize(265318, {separator: ",", round: 0}) // "265 kB" // Locale formatting filesize(265318, {locale: "de"}) // "265,32 kB" // BigInt support filesize(BigInt(1024)) // "1.02 kB" // Negative numbers filesize(-1024) // "-1.02 kB" // Exponent output filesize(1536, {output: "exponent"}) // 1 // Array output filesize(1536, {output: "array"}) // [1.54, "kB"] ``` ``` -------------------------------- ### Bits Calculation Source: https://github.com/avoidwork/filesize.js/blob/master/docs/API.md Shows how to calculate file sizes in bits instead of bytes. ```APIDOC ## bits Calculate in bits instead of bytes. ```javascript filesize(1024, {bits: true}) // "8.19 kbit" filesize(1024, {bits: true, base: 2}) // "8 Kibit" ``` ``` -------------------------------- ### Base Option Source: https://github.com/avoidwork/filesize.js/blob/master/docs/API.md Configures the number base for calculations (2 for binary, 10 for decimal). ```APIDOC ## base Number base for calculations: - `-1` (default): Auto-detect based on standard - `2`: Binary (1024) - uses IEC symbols (KiB, MiB, GiB) - `10`: Decimal (1000) ```javascript filesize(1024, {base: 2}) // "1 KiB" (binary, IEC symbols) filesize(1024, {base: 10}) // "1.02 kB" (decimal, SI symbols) ``` ``` -------------------------------- ### Using String Input Source: https://github.com/avoidwork/filesize.js/blob/master/docs/API.md The filesize function can accept a string representation of a number of bytes. It automatically handles leading/trailing whitespace and converts the value to a human-readable format. ```APIDOC ## String Input ### Description Formats a byte size provided as a string into a human-readable format. ### Method filesize(string) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript filesize("1024") // "1.02 kB" filesize("1536.5") // "1.54 kB" filesize(" 1024 ") // "1.02 kB" ``` ### Response #### Success Response (200) - **formatted_size** (string) - The human-readable string representation of the byte size. ``` -------------------------------- ### Filesize Conversion with Locale Formatting Source: https://github.com/avoidwork/filesize.js/blob/master/docs/API.md Formats the output according to a specified locale, using `locale` for the locale string. This affects decimal separators and grouping. ```javascript filesize(265318, {locale: "de"}) // "265,32 kB" ``` -------------------------------- ### Filesize Conversion to Exponent Output Source: https://github.com/avoidwork/filesize.js/blob/master/docs/API.md Returns only the exponent of the file size, where 0 represents bytes, 1 represents kilobytes/kibibytes, and so on. Useful for calculations or comparisons. ```javascript filesize(1536, {output: "exponent"}) // 1 filesize(1048576, {output: "exponent", base: 2}) // 2 ``` -------------------------------- ### Filesize Conversion with Full Form Names Source: https://github.com/avoidwork/filesize.js/blob/master/docs/API.md Displays the full names of units (e.g., 'kilobytes' instead of 'kB') by setting the `fullform` option to true. ```javascript filesize(1024, {fullform: true}) // "1.02 kilobytes" ```