filesize vs humanize-bytes vs pretty-bytes
Formatting Byte Sizes for User Interfaces
filesizehumanize-bytespretty-bytesSimilar Packages:

Formatting Byte Sizes for User Interfaces

The filesize, humanize-bytes, and pretty-bytes libraries are specialized utilities designed to convert raw byte integers into human-readable strings (e.g., turning 1024 into 1 KB). While they share a common goal, they differ significantly in flexibility, configuration depth, and output style. filesize offers the most granular control over formatting, bases, and rounding, making it suitable for complex data tables or technical dashboards. pretty-bytes focuses on concise, opinionated defaults ideal for general UI elements like file lists or download progress. humanize-bytes provides a straightforward, lightweight alternative but requires careful evaluation regarding its current maintenance status compared to the other two.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
filesize01,70858.4 kB12 months agoBSD-3-Clause
humanize-bytes03-011 years agoMIT
pretty-bytes01,30515.9 kB02 days agoMIT

Formatting Byte Sizes: filesize vs humanize-bytes vs pretty-bytes

When displaying storage capacity, file sizes, or network transfer rates to users, raw bytes (like 1536000) are meaningless. Developers need to convert these numbers into readable formats like "1.5 MB". While this seems simple, differences in rounding, base calculation (binary vs. decimal), and localization can lead to inconsistent user experiences. The filesize, humanize-bytes, and pretty-bytes packages solve this problem but take different approaches to flexibility and defaults.

šŸŽ›ļø Configuration and Flexibility

filesize is built for power users who need exact control over every aspect of the output string. It allows you to define the number of decimal places, the base (binary or decimal), the output format (string, object, or array), and even custom spacer characters.

import { filesize } from 'filesize';

// Default usage
filesize(1024); 
// Output: "1 kB"

// Custom configuration: 2 decimal places, binary base (1024), no spacer
filesize(1024, { 
  base: 2, 
  round: 2, 
  spacer: "" 
}); 
// Output: "1.00KiB"

// Returning an object for custom rendering
filesize(1024, { output: "object" }); 
// Output: { value: 1, symbol: "kB", ... }

pretty-bytes takes an opinionated approach. It aims to provide the most readable string with minimal configuration. You can specify the number of significant digits or force a specific unit, but it generally discourages deep customization to maintain consistency.

import prettyBytes from 'pretty-bytes';

// Default usage
prettyBytes(1024);
// Output: "1 kB"

// Limiting significant digits
prettyBytes(1025, { maximumSignificantDigits: 3 });
// Output: "1.03 kB"

// Forcing a specific unit
prettyBytes(1024, { unit: 'megabyte' });
// Output: "0.001 MB"

humanize-bytes offers a simpler API with fewer configuration options. It typically accepts the number and an optional options object for precision, focusing on getting a standard string quickly without the extensive feature set of filesize.

import humanizeBytes from 'humanize-bytes';

// Default usage
humanizeBytes(1024);
// Output: "1 KB"

// With precision option
humanizeBytes(1024, { precision: 2 });
// Output: "1.00 KB"

šŸ“ Binary (1024) vs Decimal (1000) Bases

A common source of bugs in file formatting is mixing up binary (KiB, MiB) and decimal (KB, MB) units. Operating systems often disagree on which to use.

filesize lets you explicitly toggle this behavior. By default, it often uses decimal (SI) standards, but you can switch to binary (IEC) easily.

import { filesize } from 'filesize';

const size = 1048576; // 1024 * 1024

// Decimal (SI) - Default in many configs
filesize(size, { base: 10 }); 
// Output: "1.05 MB"

// Binary (IEC)
filesize(size, { base: 2 }); 
// Output: "1 MiB"

pretty-bytes also supports this distinction but exposes it through the binary option. This is crucial when matching OS-specific reporting (e.g., macOS uses binary, while some network tools use decimal).

import prettyBytes from 'pretty-bytes';

const size = 1048576;

// Decimal (Default)
prettyBytes(size);
// Output: "1.05 MB"

// Binary
prettyBytes(size, { binary: true });
// Output: "1 MiB"

humanize-bytes generally defaults to one standard (often binary or decimal depending on the version and implementation details) and may offer less explicit control over switching bases compared to the other two. Developers must verify the default behavior in their specific version to ensure it matches their application's requirements.

import humanizeBytes from 'humanize-bytes';

// Behavior depends on library version defaults
// Often requires checking docs to confirm if 1024 or 1000 is used for 'KB'
humanizeBytes(1048576);
// Output varies: "1 MB" or "1.05 MB" depending on base logic

šŸŒ Localization and Symbols

How units are labeled matters for international audiences. Some libraries use "KB", others "kB", and some support full words like "Kilobytes".

filesize has robust support for custom symbols and locales. You can pass a locale string to format numbers according to regional standards (e.g., using commas vs. periods for decimals) and even override unit symbols.

import { filesize } from 'filesize';

// Using German locale for number formatting
filesize(1024.5, { locale: 'de-DE' });
// Output: "1,02 kB" (Note the comma)

// Custom symbols
filesize(1024, { symbols: { kb: "Ko" } }); // French convention example
// Output: "1 Ko"

pretty-bytes handles localization primarily through the locale option, which formats the number part of the string. It sticks to standard unit abbreviations but ensures the numeric portion respects the user's region.

import prettyBytes from 'pretty-bytes';

// French locale
prettyBytes(1024.5, { locale: 'fr-FR' });
// Output: "1,03 kB"

humanize-bytes typically provides basic number formatting but may lack the deep locale integration found in filesize. It is best suited for applications where default English formatting is acceptable or where custom post-processing is planned.

import humanizeBytes from 'humanize-bytes';

// Basic usage, locale support may be limited or absent depending on version
humanizeBytes(1024.5);
// Output: "1.02 KB"

āš ļø Maintenance and Deprecation Status

Before adding any dependency, checking its maintenance status is critical.

  • filesize: Actively maintained. It is a mature library with regular updates, strong TypeScript support, and a large user base. It is safe for long-term projects.
  • pretty-bytes: Actively maintained by a prominent developer in the JavaScript ecosystem. It is stable, well-tested, and widely used in modern tooling.
  • humanize-bytes: Caution advised. This package has seen significantly less activity compared to the others. In some contexts, similar packages have been deprecated in favor of more robust alternatives. Always check the latest npm page and repository for deprecation notices before selecting this for a new architecture. If the repository is archived or has no recent commits, prefer filesize or pretty-bytes.

šŸ†š Summary of Differences

Featurefilesizepretty-byteshumanize-bytes
Primary GoalMaximum flexibility & controlSensible defaults & simplicityBasic conversion
Base ControlExplicit (base: 2 or 10)Explicit (binary: true)Limited / Implicit
Output FormatsString, Object, Array, ExponentString onlyString only
LocalizationAdvanced (Locale + Custom Symbols)Standard (Locale)Basic / None
Maintenanceāœ… Activeāœ… Activeāš ļø Verify Status

šŸ’” Final Recommendation

For complex enterprise applications where you need to match specific design systems, support multiple locales deeply, or display data in non-standard ways (like returning objects for custom rendering), filesize is the superior choice. Its API is verbose but powerful.

For standard web applications, dashboards, and UI components where you just need a clean, readable string without spending time configuring options, pretty-bytes is the ideal default. It balances size, features, and ease of use perfectly.

Avoid humanize-bytes for new projects unless you have a specific legacy constraint, as the other two options offer better long-term stability, clearer documentation, and more active community support. Always prioritize libraries that are actively maintained to ensure security and compatibility with future JavaScript standards.

How to Choose: filesize vs humanize-bytes vs pretty-bytes

  • filesize:

    Choose filesize when you need precise control over output formatting, such as enforcing specific decimal places, switching between binary (1024) and decimal (1000) bases, or customizing spacer characters. It is the best fit for enterprise dashboards, data-heavy tables, or scenarios where consistency across different locales and units is critical.

  • humanize-bytes:

    Choose humanize-bytes only if you are maintaining a legacy project that already depends on it or if you require a very specific, simple output format that matches its defaults exactly. For new projects, proceed with caution and verify its current maintenance status, as more robust and actively updated alternatives exist in the ecosystem.

  • pretty-bytes:

    Choose pretty-bytes for modern web applications where you need a reliable, zero-config solution that looks good out of the box. It is ideal for file uploaders, disk space indicators, and general UI components where standard formatting (like '1.5 MB') is preferred over highly customized technical strings.

README for filesize

filesize

npm version Node.js Version License Build Status

A lightweight, high-performance file size utility that converts bytes to human-readable strings. Zero dependencies. 100% test coverage.

Why filesize?

  • Zero dependencies - Pure JavaScript, no external packages
  • 100% test coverage - Reliable, well-tested codebase
  • TypeScript ready - Full type definitions included
  • Multiple standards - SI, IEC, and JEDEC support
  • Localization - Intl API for international formatting
  • BigInt support - Handle extremely large file sizes
  • Functional API - Partial application for reusable formatters
  • Browser & Node.js - Works everywhere

Installation

npm install filesize

TypeScript

Fully typed with TypeScript definitions included:

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' });

Usage

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"

Partial Application

import {partial} from "filesize";

const formatBinary = partial({standard: "iec"});
formatBinary(1024); // "1 KiB"
formatBinary(1048576); // "1 MiB"

Options

OptionTypeDefaultDescription
bitsbooleanfalseCalculate bits instead of bytes
basenumber-1Number base (2 for binary, 10 for decimal, -1 for auto)
roundnumber2Decimal places to round
localestring|boolean""Locale for formatting, true for system locale
localeOptionsObject{}Additional locale options
separatorstring""Custom decimal separator
spacerstring" "Value-unit separator
symbolsObject{}Custom unit symbols
standardstring""Unit standard (si, iec, jedec)
outputstring"string"Output format (string, array, object, exponent)
fullformbooleanfalseUse full unit names
fullformsArray[]Custom full unit names
exponentnumber-1Force specific exponent (-1 for auto)
roundingMethodstring"round"Math method (round, floor, ceil)
precisionnumber0Significant digits (0 for auto)
padbooleanfalsePad decimal places

Output Formats

// String (default)
filesize(1536); // "1.54 kB"

// Array
filesize(1536, {output: "array"}); // [1.54, "kB"]

// Object
filesize(1536, {output: "object"});
// {value: 1.54, symbol: "kB", exponent: 1, unit: "kB"}

// Exponent
filesize(1536, {output: "exponent"}); // 1

Standards

// 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"

Examples

// Bits
filesize(1024, {bits: true}); // "8.19 kbit"
filesize(1024, {bits: true, base: 2}); // "8 Kibit"

// Full form
filesize(1024, {fullform: true}); // "1.02 kilobytes"
filesize(1024, {base: 2, fullform: true}); // "1 kibibyte"

// Custom separator
filesize(265318, {separator: ","}); // "265,32 kB"

// Padding
filesize(1536, {round: 3, pad: true}); // "1.536 kB"

// Precision
filesize(1536, {precision: 3}); // "1.54 kB"

// Locale
filesize(265318, {locale: "de"}); // "265,32 kB"

// Custom symbols
filesize(1, {symbols: {B: "Š‘"}}); // "1 Š‘"

// BigInt support
filesize(BigInt(1024)); // "1.02 kB"

// Negative numbers
filesize(-1024); // "-1.02 kB"

Error Handling

try {
  filesize("invalid");
} catch (error) {
  // TypeError: "Invalid number"
}

try {
  filesize(1024, {roundingMethod: "invalid"});
} catch (error) {
  // TypeError: "Invalid rounding method"
}

Testing

npm test              # Run all tests (lint + node:test)
npm run test:watch    # Live test watching

100% test coverage with 149 tests:

--------------|---------|----------|---------|---------|-------------------
File          | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
--------------|---------|----------|---------|---------|-------------------
All files     |     100 |      100 |     100 |     100 |                   
 constants.js |     100 |      100 |     100 |     100 |                   
 filesize.js  |     100 |      100 |     100 |     100 |                   
 helpers.js   |     100 |      100 |     100 |     100 |                   
--------------|---------|----------|---------|---------|-------------------

Development

npm install         # Install dependencies
npm run dev         # Development mode with live reload
npm run build       # Build distributions
npm run lint        # Check code style
npm run lint:fix    # Auto-fix linting issues

Project Structure

filesize.js/
ā”œā”€ā”€ src/
│   ā”œā”€ā”€ filesize.js      # Main implementation (285 lines)
│   ā”œā”€ā”€ helpers.js       # Helper functions (215 lines)
│   └── constants.js     # Constants (81 lines)
ā”œā”€ā”€ tests/
│   └── unit/
ā”œā”€ā”€ dist/                # Built distributions
└── types/               # TypeScript definitions

Performance

  • Basic conversions: ~16-27M ops/sec
  • With options: ~5-13M ops/sec
  • Locale formatting: ~91K ops/sec (use sparingly)

Optimization tips:

  1. Cache partial() formatters for reuse
  2. Avoid locale formatting in performance-critical code
  3. Use object output for fastest structured data access

Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

Changelog

See CHANGELOG.md for a history of changes.

License

Copyright (c) 2026 Jason Mulligan
Licensed under the BSD-3 license.