bytes vs filesize vs pretty-bytes
Formatting Byte Values in JavaScript Applications
bytesfilesizepretty-bytesSimilar Packages:

Formatting Byte Values in JavaScript Applications

bytes, filesize, and pretty-bytes are utility libraries designed to convert raw numeric byte values into human-readable strings (e.g., turning 1024 into 1 KB). While they share a core purpose, they differ significantly in flexibility, parsing capabilities, and default styling. bytes is a dual-purpose tool often found in Node.js backends that handles both formatting and parsing. filesize offers the deepest configuration options for custom units and standards. pretty-bytes focuses on sensible defaults and modern locale support, making it a strong choice for frontend user interfaces.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
bytes047412.3 kB12-MIT
filesize01,70964.4 kB012 days agoBSD-3-Clause
pretty-bytes01,31125.1 kB011 hours agoMIT

bytes vs filesize vs pretty-bytes: Formatting Byte Values in JavaScript

Converting raw byte counts into human-readable strings is a common task in web development — whether you are displaying file sizes to users, logging memory usage, or validating HTTP headers. While bytes, filesize, and pretty-bytes all solve this problem, they take different approaches regarding flexibility, parsing capabilities, and environment fit. Let's break down how they handle real-world scenarios.

🧮 Core Usage: Formatting Numbers

All three packages accept a number and return a string, but their default output styles differ.

bytes produces compact output without spaces between numbers and units.

import bytes from 'bytes';

console.log(bytes(1024)); 
// Output: "1KB"

console.log(bytes(1500)); 
// Output: "1.5KB"

filesize includes a space by default and offers more readable decimals.

import { filesize } from 'filesize';

console.log(filesize(1024)); 
// Output: "1.02 KB"

console.log(filesize(1500)); 
// Output: "1.5 KB"

pretty-bytes focuses on clean, localized output with spaces.

import prettyBytes from 'pretty-bytes';

console.log(prettyBytes(1024)); 
// Output: "1.02 kB"

console.log(prettyBytes(1500)); 
// Output: "1.5 kB"

🔁 Parsing vs Formatting: Bidirectional vs One-Way

A key architectural difference is whether the library can convert strings back to numbers.

bytes supports bidirectional conversion. If you pass a string, it returns a number.

import bytes from 'bytes';

// Formatting
console.log(bytes(1024)); // "1KB"

// Parsing
console.log(bytes('1KB')); // 1024
console.log(bytes('1mb')); // 1048576

filesize is strictly for formatting. It does not parse strings back to numbers.

import { filesize } from 'filesize';

// Formatting
console.log(filesize(1024)); // "1.02 KB"

// Parsing (Not supported)
// filesize('1KB') would throw an error or return invalid

pretty-bytes is also strictly for formatting. It expects a number input.

import prettyBytes from 'pretty-bytes';

// Formatting
console.log(prettyBytes(1024)); // "1.02 kB"

// Parsing (Not supported)
// prettyBytes('1KB') would return "NaN B" or similar

⚙️ Configuration: Customization Depth

When you need to control rounding, units, or standards, the packages diverge sharply.

bytes has limited options, mostly focused on casing and separators.

import bytes from 'bytes';

bytes(1000, { 
  unitSeparator: ' ', 
  decimalPlaces: 2 
}); 
// Output: "1.00 KB"

filesize offers extensive control over bases, bits, and symbols.

import { filesize } from 'filesize';

filesize(1000, { 
  base: 2, // IEC standard (KiB)
  bits: true, // Show bits instead of bytes
  round: 1 
}); 
// Output: "7.8 Kib"

pretty-bytes keeps options minimal, focusing on locale and binary standards.

import prettyBytes from 'pretty-bytes';

prettyBytes(1000, { 
  binary: true, // Use 1024 base
  locale: 'de-DE' // German locale formatting
}); 
// Output: "1,02 KiB"

🌍 Locale and Internationalization

Displaying numbers correctly for different regions matters for user-facing apps.

bytes does not support locale-aware formatting natively. You get standard dots for decimals.

import bytes from 'bytes';

// No locale option available
bytes(1000.5); 
// Output: "1KB" (rounded) or "1.001KB"

filesize supports locale options to handle decimal separators.

import { filesize } from 'filesize';

filesize(1000.5, { locale: 'de-DE' }); 
// Output: "1,00 KB" (comma separator)

pretty-bytes has robust locale support built into the core API.

import prettyBytes from 'pretty-bytes';

prettyBytes(1000.5, { locale: 'de-DE' }); 
// Output: "1,001 kB"

🖥️ Environment Fit: Backend vs Frontend

Where you run the code influences which tool makes sense.

bytes is historically tied to the Node.js ecosystem. It is common in Express middleware and server logs.

// Typical Node.js backend usage
app.use((req, res, next) => {
  const limit = bytes('5mb');
  if (req.headers['content-length'] > limit) {
    return res.status(413).send('Too Large');
  }
  next();
});

filesize works everywhere but shines in complex admin dashboards where users toggle settings.

// React dashboard component
function FileRow({ size }) {
  return (
    <td>{filesize(size, { standard: 'jedec' })}</td>
  );
}

pretty-bytes is optimized for modern frontend builds and bundle analysis tools.

// Webpack bundle analyzer or UI card
function BundleCard({ size }) {
  return (
    <div>{prettyBytes(size, { files: true })}</div>
  );
}

📊 Summary: Key Differences

Featurebytesfilesizepretty-bytes
Primary UseBackend / MiddlewareComplex UI / DashboardsFrontend / Build Tools
Parsing✅ Yes (String to Number)❌ No❌ No
Localization❌ No✅ Yes✅ Yes
CustomizationLowHighMedium
Default StyleCompact ("1KB")Spaced ("1.02 KB")Clean ("1.02 kB")

💡 The Big Picture

bytes is the utility player for Node.js developers — especially when you need to parse incoming header strings or validate sizes on the server. Its bidirectional capability saves you from writing custom parsers.

filesize is the power tool for data-heavy interfaces. If your users need to switch between bits and bytes, or require specific rounding rules, this package handles the complexity without extra code.

pretty-bytes is the modern choice for frontend displays. It respects user locales, looks clean by default, and integrates well with build tools that report bundle sizes.

Final Thought: If you are building a server API, reach for bytes. If you are building a user-facing dashboard with specific formatting needs, choose filesize. If you just need a file size to look good in a UI card with minimal fuss, pretty-bytes is the way to go.

How to Choose: bytes vs filesize vs pretty-bytes

  • bytes:

    Choose bytes if you are working in a Node.js backend environment where you need to both format output and parse incoming strings (like Content-Length headers). It is ideal for middleware, API validation, or server-side logic where bidirectional conversion is required.

  • filesize:

    Choose filesize if you need granular control over output formatting, such as switching between bits and bytes, changing base standards (JEDEC vs IEC), or customizing separators. It suits complex dashboards or admin panels where users expect specific unit conventions.

  • pretty-bytes:

    Choose pretty-bytes if you need a lightweight, frontend-focused solution that looks good out of the box with minimal configuration. It is best for build tools, bundle analyzers, or user-facing displays where standard locale formatting and clean defaults are more important than deep customization.

README for bytes

Bytes utility

NPM Version NPM Downloads Build Status Test Coverage

Utility to parse a string bytes (ex: 1TB) to bytes (1099511627776) and vice-versa.

Installation

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install bytes

Usage

var bytes = require('bytes');

bytes(number|string value, [options]): number|string|null

Default export function. Delegates to either bytes.format or bytes.parse based on the type of value.

Arguments

NameTypeDescription
valuenumber|stringNumber value to format or string value to parse
optionsObjectConversion options for format

Returns

NameTypeDescription
resultsstring|number|nullReturn null upon error. Numeric value in bytes, or string value otherwise.

Example

bytes(1024);
// output: '1KB'

bytes('1KB');
// output: 1024

bytes.format(number value, [options]): string|null

Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is rounded.

Arguments

NameTypeDescription
valuenumberValue in bytes
optionsObjectConversion options

Options

PropertyTypeDescription
decimalPlacesnumber|nullMaximum number of decimal places to include in output. Default value to 2.
fixedDecimalsboolean|nullWhether to always display the maximum number of decimal places. Default value to false
thousandsSeparatorstring|nullExample of values: ' ', ',' and '.'... Default value to ''.
unitstring|nullThe unit in which the result will be returned (B/KB/MB/GB/TB). Default value to '' (which means auto detect).
unitSeparatorstring|nullSeparator to use between number and unit. Default value to ''.

Returns

NameTypeDescription
resultsstring|nullReturn null upon error. String value otherwise.

Example

bytes.format(1024);
// output: '1KB'

bytes.format(1000);
// output: '1000B'

bytes.format(1000, {thousandsSeparator: ' '});
// output: '1 000B'

bytes.format(1024 * 1.7, {decimalPlaces: 0});
// output: '2KB'

bytes.format(1024, {unitSeparator: ' '});
// output: '1 KB'

bytes.parse(string|number value): number|null

Parse the string value into an integer in bytes. If no unit is given, or value is a number, it is assumed the value is in bytes.

Supported units and abbreviations are as follows and are case-insensitive:

  • b for bytes
  • kb for kilobytes
  • mb for megabytes
  • gb for gigabytes
  • tb for terabytes
  • pb for petabytes

The units are in powers of two, not ten. This means 1kb = 1024b according to this parser.

Arguments

NameTypeDescription
valuestring|numberString to parse, or number in bytes.

Returns

NameTypeDescription
resultsnumber|nullReturn null upon error. Value in bytes otherwise.

Example

bytes.parse('1KB');
// output: 1024

bytes.parse('1024');
// output: 1024

bytes.parse(1024);
// output: 1024

License

MIT