CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-filesize

JavaScript library to generate a human readable String describing the file size

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

Filesize

Filesize is a JavaScript library that converts numeric byte values to human-readable file size strings with appropriate units. It supports multiple unit standards (SI, IEC, JEDEC), customizable formatting options, and works in both Node.js and browser environments.

Package Information

  • Package Name: filesize
  • Package Type: npm
  • Language: JavaScript (ES modules with TypeScript definitions)
  • Installation: npm install filesize

Core Imports

import { filesize, partial } from "filesize";

For CommonJS:

const { filesize, partial } = require("filesize");

Basic Usage

import { filesize } from "filesize";

// Basic usage - converts bytes to human-readable format
filesize(1000)        // "1 kB" (decimal by default)
filesize(1024)        // "1.02 kB"
filesize(1048576)     // "1.05 MB"

// Use binary standard (1024-based)
filesize(1024, { standard: "iec" })     // "1 KiB"
filesize(1048576, { standard: "iec" })  // "1 MiB"

// Convert to bits instead of bytes
filesize(1000, { bits: true })   // "8 kbit"

// Custom formatting
filesize(1536, { round: 1 })     // "1.5 kB"
filesize(1536, { round: 0 })     // "2 kB"

// Different output formats
filesize(1000, { output: "array" })   // [1, "kB"]
filesize(1000, { output: "object" })  // {value: 1, symbol: "kB", exponent: 1, unit: "kB"}

Capabilities

Main Conversion Function

Converts a file size in bytes to a human-readable string with appropriate units.

/**
 * Converts a file size in bytes to a human-readable string with appropriate units
 * @param arg - The file size in bytes to convert
 * @param options - Configuration options for formatting
 * @returns Formatted file size based on output option
 * @throws {TypeError} When arg is not a valid number or roundingMethod is invalid
 */
function filesize<T extends FilesizeOptions = {}>(
  arg: number | string | bigint,
  options?: T
): FilesizeReturn<T>;

Usage Examples:

// Basic conversions
filesize(1024)                    // "1.02 kB"
filesize(1000000)                 // "1 MB"
filesize(1073741824)              // "1.07 GB"

// Negative numbers
filesize(-1000)                   // "-1 kB"

// Different standards
filesize(1024, { standard: "iec" })    // "1 KiB" (binary)
filesize(1000, { standard: "si" })     // "1 kB" (decimal)
filesize(1024, { standard: "jedec" })  // "1 KB" (binary with decimal symbols)

// Bits vs bytes
filesize(1000, { bits: true })         // "8 kbit"
filesize(1024, { bits: true, standard: "iec" }) // "8 Kibit"

// Precision control
filesize(1536, { round: 0 })           // "2 kB"
filesize(1536, { round: 1 })           // "1.5 kB"
filesize(1536, { round: 3 })           // "1.536 kB"

// Rounding methods
filesize(1536, { roundingMethod: "floor" })  // "1.53 kB"
filesize(1536, { roundingMethod: "ceil" })   // "1.54 kB"

// Different output formats
filesize(1000, { output: "string" })   // "1 kB" (default)
filesize(1000, { output: "array" })    // [1, "kB"]
filesize(1000, { output: "object" })   // {value: 1, symbol: "kB", exponent: 1, unit: "kB"}
filesize(1000, { output: "exponent" }) // 1

// Localization
filesize(1536.7, { locale: "de-DE" })  // "1,54 kB"
filesize(1536.7, { locale: true })     // Uses system locale

// Custom separators and spacing
filesize(1536, { separator: "," })     // "1,54 kB"
filesize(1536, { spacer: "_" })        // "1.54_kB"

// Full unit names
filesize(1024, { fullform: true, standard: "iec" })  // "1 kibibyte"
filesize(2048, { fullform: true, standard: "iec" })  // "2 kibibytes"

// Custom symbols
filesize(1024, { symbols: { "kB": "kilobytes" } })   // "1.02 kilobytes"

// Padding decimal places
filesize(1000, { pad: true, round: 2 }) // "1.00 kB"

Architecture

Filesize is built around several key components and design patterns:

  • Core Algorithm: Logarithmic calculation to determine appropriate unit exponent, with special handling for edge cases like zero and negative values
  • Unit Standards System: Three distinct unit systems (SI decimal, IEC binary, JEDEC binary) with configurable base calculations (powers of 1000 vs 1024)
  • Output Format Engine: Flexible output system supporting string, array, object, and exponent formats with conditional return types
  • Localization Layer: Comprehensive internationalization support using JavaScript's built-in Intl.NumberFormat API
  • Partial Application Pattern: Functional programming approach allowing preset configurations for repeated use cases
  • Type Safety: Full TypeScript integration with generic type preservation and conditional return types

The library uses a single-pass algorithm that calculates the appropriate unit scale, applies formatting rules, and returns the result in the requested format, making it both performant and memory-efficient.

Partial Application Function

Creates a partially applied version of filesize with preset options for functional programming patterns.

/**
 * Creates a partially applied version of filesize with preset options
 * @param options - Default options to apply to the returned function
 * @returns A function that takes a file size and returns formatted output
 */
function partial<T extends FilesizeOptions = {}>(
  options?: T
): (arg: number | string | bigint) => FilesizeReturn<T>;

Usage Examples:

import { partial } from "filesize";

// Create formatters with preset options
const formatBinary = partial({ standard: "iec", round: 1 });
const formatBits = partial({ bits: true, round: 0 });
const formatCompact = partial({ round: 0, spacer: "" });

// Use preset formatters
formatBinary(1024)    // "1.0 KiB"
formatBinary(2048)    // "2.0 KiB"

formatBits(1000)      // "8 kbit"
formatBits(2000)      // "16 kbit"

formatCompact(1536)   // "2kB"
formatCompact(2048)   // "2kB"

// Create object output formatter
const toObject = partial({ output: "object" });
toObject(1000);       // {value: 1, symbol: "kB", exponent: 1, unit: "kB"}

Types

/**
 * Options interface for configuring filesize behavior
 */
interface FilesizeOptions {
  /** If true, calculates bits instead of bytes */
  bits?: boolean;
  /** If true, pads decimal places to match round parameter */
  pad?: boolean;
  /** Number base (2 for binary, 10 for decimal, -1 for auto) */
  base?: number;
  /** Number of decimal places to round to */
  round?: number;
  /** Locale for number formatting, true for system locale */
  locale?: string | boolean;
  /** Additional options for locale formatting */
  localeOptions?: Intl.NumberFormatOptions;
  /** Custom decimal separator */
  separator?: string;
  /** String to separate value and unit */
  spacer?: string;
  /** Custom unit symbols */
  symbols?: Record<string, string>;
  /** Unit standard to use (SI, IEC, JEDEC) */
  standard?: "si" | "iec" | "jedec" | "";
  /** Output format: "string", "array", "object", or "exponent" */
  output?: "string" | "array" | "object" | "exponent";
  /** If true, uses full unit names instead of abbreviations */
  fullform?: boolean;
  /** Custom full unit names */
  fullforms?: string[];
  /** Force specific exponent (-1 for auto) */
  exponent?: number;
  /** Math rounding method to use */
  roundingMethod?: "round" | "floor" | "ceil";
  /** Number of significant digits (0 for auto) */
  precision?: number;
}

/**
 * Object format return type when output is "object"
 */
interface FilesizeObject {
  /** The numeric value */
  value: number | string;
  /** The unit symbol */
  symbol: string;
  /** The exponent used in calculation */
  exponent: number;
  /** The original unit before symbol customization */
  unit: string;
}

/**
 * Array format return type when output is "array"
 */
type FilesizeArray = [number | string, string];

/**
 * Return type based on output option
 */
type FilesizeReturn<T extends FilesizeOptions = {}> =
  T['output'] extends "object" ? FilesizeObject :
  T['output'] extends "array" ? FilesizeArray :
  T['output'] extends "exponent" ? number :
  string;

Error Handling

The library throws TypeError exceptions in two cases:

  1. Invalid Input: When the input argument is not a valid number

    filesize("invalid")  // TypeError: "Invalid number"
    filesize(undefined)  // TypeError: "Invalid number"
  2. Invalid Rounding Method: When an unsupported rounding method is specified

    filesize(1000, { roundingMethod: "invalid" as any })  // TypeError: "Invalid rounding method"

Standards Reference

  • SI (Decimal): Uses powers of 1000 (kB, MB, GB, TB, etc.)
  • IEC (Binary): Uses powers of 1024 with binary prefixes (KiB, MiB, GiB, TiB, etc.)
  • JEDEC (Binary): Uses powers of 1024 with decimal symbols (KB, MB, GB, TB, etc.)

Default behavior uses decimal (powers of 1000) with JEDEC symbols unless otherwise specified.

docs

index.md

tile.json