PHPackages                             avoidwork/filesize.js - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [File &amp; Storage](/categories/file-storage)
4. /
5. avoidwork/filesize.js

ActiveLibrary[File &amp; Storage](/categories/file-storage)

avoidwork/filesize.js
=====================

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

6.2.1(5y ago)1.7k38299BSD-3-ClauseJavaScriptCI passing

Since Jan 4Pushed 2mo ago15 watchersCompare

[ Source](https://github.com/avoidwork/filesize.js)[ Packagist](https://packagist.org/packages/avoidwork/filesize.js)[ Docs](http://filesizejs.com)[ GitHub Sponsors](https://github.com/avoidwork)[ RSS](/packages/avoidwork-filesizejs/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (46)Used By (0)

filesize.js
===========

[](#filesizejs)

[![downloads](https://camo.githubusercontent.com/0916dd67373a7c97500b7268e0634160ef1859005908220b676e79bd040899f7/68747470733a2f2f696d672e736869656c64732e696f2f6e706d2f64742f66696c6573697a652e737667)](https://www.npmjs.com/package/filesize)[![npm version](https://camo.githubusercontent.com/cd91e9e58f9ac52c99873a100e4112c5ed06f05fc55ffbaa82578865fed33188/68747470733a2f2f62616467652e667572792e696f2f6a732f66696c6573697a652e737667)](https://badge.fury.io/js/filesize)[![Node.js Version](https://camo.githubusercontent.com/1a716e5ec9b40770f43ca70e9b63b13104c7fbbb45379ceb854ae2d96a908ad1/68747470733a2f2f696d672e736869656c64732e696f2f6e6f64652f762f66696c6573697a652e737667)](https://nodejs.org/)[![License](https://camo.githubusercontent.com/b3775a2de17853a90995faa104f941eef3ad3c40cc89e34b8b1eaea014614d4e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d425344253230332d2d436c617573652d626c75652e737667)](https://opensource.org/licenses/BSD-3-Clause)[![Build Status](https://github.com/avoidwork/woodland/actions/workflows/ci.yml/badge.svg)](https://github.com/avoidwork/filesize.js/actions)

A lightweight, high-performance file size utility for JavaScript that converts bytes to human-readable strings. Works in both Node.js and browser environments with comprehensive format support.

Installation
------------

[](#installation)

```
npm install filesize
```

Usage
-----

[](#usage)

### ES Modules

[](#es-modules)

```
import {filesize} from "filesize";
filesize(265318, {standard: "jedec"}); // "259.1 KB"
```

### CommonJS

[](#commonjs)

```
const {filesize} = require("filesize");
filesize(1024); // "1.02 kB"
```

### Partial Application

[](#partial-application)

```
import {partial} from "filesize";
const size = partial({standard: "jedec"});
size(265318); // "259.1 KB"
```

Parameters
----------

[](#parameters)

- **input** `{Number|String|BigInt}` - The value to convert (required)
- **options** `{Object}` - Configuration object (optional)

### Options Object

[](#options-object)

- **base** `{Number}` - Number base, default is `10`
- **bits** `{Boolean}` - Enables `bit` sizes, default is `false`
- **exponent** `{Number}` - Specifies the symbol via exponent, e.g. `2` is `MB` for base 2, default is `-1`
- **fullform** `{Boolean}` - Enables full form of unit of measure, default is `false`
- **fullforms** `{Array}` - Array of full form overrides, default is `[]`
- **locale** `{String|Boolean}` - BCP 47 language tag to specify a locale, or `true` to use default locale, default is `""`
- **localeOptions** `{Object}` - Dictionary of options defined by ECMA-402 ([Number.prototype.toLocaleString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString))
- **output** `{String}` - Output of function (`array`, `exponent`, `object`, or `string`), default is `string`
- **pad** `{Boolean}` - Decimal place end padding, default is `false`
- **precision** `{Number}` - Sets precision of numerical output, default is `0`
- **round** `{Number}` - Decimal place, default is `2`
- **roundingMethod** `{String}` - Rounding method, can be `round`, `floor`, or `ceil`, default is `round`
- **separator** `{String}` - Decimal separator character, default is an empty string
- **spacer** `{String}` - Character between the `result` and `symbol`, default is `" "`
- **standard** `{String}` - Standard unit of measure, can be `iec`, `jedec`, or `si`. Default is `si` (base 10)
- **symbols** `{Object}` - Dictionary of IEC/JEDEC symbols to replace for localization

### Input Validation

[](#input-validation)

The function validates input and throws `TypeError` for invalid values:

```
// Invalid input will throw TypeError
try {
  filesize("invalid");
} catch (error) {
  console.error(error.message); // "Invalid input"
}

try {
  filesize(NaN);
} catch (error) {
  console.error(error.message); // "Invalid input"
}
```

Testing
-------

[](#testing)

filesize.js maintains **100% test coverage** across all metrics with a comprehensive test suite of 47 test cases:

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

### Running Tests

[](#running-tests)

```
# Run all tests (linting + unit tests)
npm test

# Run only unit tests
npm run mocha
```

### Test Coverage

[](#test-coverage)

The test suite comprehensively covers:

- **Basic functionality**: Core conversion logic and edge cases
- **Output formats**: All output types (string, array, object, exponent)
- **Standards support**: IEC, JEDEC, and SI standards with different bases
- **Bit conversion**: Bits vs bytes with auto-increment logic
- **Precision handling**: Rounding methods and decimal precision
- **Localization**: Locale formatting and custom symbols
- **Error handling**: Invalid inputs and boundary conditions
- **Partial functions**: All option combinations with curried functions

Performance Benchmarks
----------------------

[](#performance-benchmarks)

filesize.js is optimized for high performance with comprehensive benchmarks covering various usage patterns:

### 🚀 Performance Overview

[](#-performance-overview)

ScenarioOperations/secNotes**Basic conversion**~16-27M ops/secFastest operations (large numbers)**Small numbers**~18-20M ops/secConsistent performance**With options**~5-13M ops/secDepends on option complexity**Locale formatting**~91K ops/secMost expensive operation**Stress testing**~2-10M ops/secHandles edge cases gracefully### 📊 Detailed Benchmark Results

[](#-detailed-benchmark-results)

#### Basic Performance (5-run average)

[](#basic-performance-5-run-average)

- **filesize(0)**: 18.6M ops/sec
- **filesize(512)**: 20.3M ops/sec
- **filesize(1024)**: 18.7M ops/sec
- **filesize(1048576)**: 23.5M ops/sec
- **filesize(1073741824)**: 23.6M ops/sec
- **filesize(1099511627776)**: 26.9M ops/sec
- **With bits=true**: 16.8M ops/sec
- **With standard="iec"**: 16.6M ops/sec
- **With round=4**: 13.4M ops/sec

#### Options Performance Impact

[](#options-performance-impact)

- **bits=true**: 12.5M ops/sec
- **pad=true**: 5.6M ops/sec
- **locale="en-US"**: 91K ops/sec (significant overhead)
- **standard="iec"**: 8.8M ops/sec
- **standard="jedec"**: 9.0M ops/sec
- **output="array"**: 10.2M ops/sec
- **output="object"**: 9.2M ops/sec
- **fullform=true**: 7.8M ops/sec
- **precision=3**: 6.3M ops/sec
- **separator=","**: 7.2M ops/sec

#### Stress Test Results

[](#stress-test-results)

- **Edge cases**: 2.3M ops/sec (90% success rate)
- **Very large numbers**: 4.6M ops/sec (100% success)
- **Very small numbers**: 10.4M ops/sec (100% success)
- **Negative numbers**: 5.4M ops/sec (100% success)
- **Random options**: 2.3M ops/sec (100% success)
- **BigInt values**: 3.7M ops/sec (100% success)
- **Memory pressure**: 49K ops/sec (100% success)
- **Error conditions**: 715K ops/sec (~40% success rate)

#### Partial Function Performance

[](#partial-function-performance)

Partial functions maintain excellent performance with minimal overhead:

- **Acceptable overhead**: 1.1-1.4x slower for most configurations
- **Locale partials**: Significant overhead (~180x slower) due to locale formatting
- **Creation cost**: Amortized across multiple uses

### 💡 Performance Insights

[](#-performance-insights)

**Excellent Performance (&gt;10M ops/sec)**

- Basic conversions with minimal options
- Large number processing (1TB+ values)
- Standard output formats (string, array, object)
- IEC and JEDEC standards

**Good Performance (1-10M ops/sec)**

- Complex option combinations
- Precision and rounding operations
- Fullform output
- Stress test scenarios

**Use Sparingly (&lt;100K ops/sec)**

- Locale formatting (significant overhead ~91K ops/sec)
- Memory pressure conditions

### 🎯 Optimization Tips

[](#-optimization-tips)

1. **Cache partial functions** for repeated operations with same options
2. **Avoid locale formatting** in performance-critical code
3. **Use object output** for fastest structured data
4. **Batch similar operations** together
5. **Profile your specific usage patterns**

### Running Benchmarks

[](#running-benchmarks)

```
# Run all benchmarks
cd benchmarks && node index.js

# Run specific benchmark
node benchmarks/basic-performance.js

# With garbage collection (more accurate)
node --expose-gc benchmarks/index.js
```

### 🔥 Recent Performance Optimizations (v11.0.8)

[](#-recent-performance-optimizations-v1108)

The latest version includes significant performance improvements:

- **Pre-computed lookup tables** for Math operations (eliminates expensive `Math.pow()` calls)
- **Optimized base/standard logic** with reduced branching
- **Fast path for zero values** with minimal computation
- **Cached object property access** to reduce repeated lookups
- **Improved mathematical operations** with conditional calculations

**Overall performance improvement: 30-70% faster** across common use cases while maintaining full backward compatibility.

*Benchmarks run on macOS ARM64, Node.js v24.8.0, 12 CPU cores, 24GB RAM (5-run averages)*

API Reference
-------------

[](#api-reference)

### Functions

[](#functions)

#### filesize(input, options)

[](#filesizeinput-options)

Converts a numeric value to a human-readable file size string.

**Parameters:**

- `input` `{Number|String|BigInt}` - The value to convert
- `options` `{Object}` - Configuration options (optional)

**Returns:** `{String|Array|Object|Number}` - Formatted size based on output option

```
filesize(500); // "500 B"
filesize(1024, {base: 2}); // "1 KiB"
filesize(265318, {output: "array"}); // [265.32, "kB"]
```

**See also:** partial()

#### partial(options)

[](#partialoptions)

Creates a pre-configured filesize function with options applied.

**Parameters:**

- `options` `{Object}` - Configuration options to apply

**Returns:** `{Function}` - New function with options pre-applied

```
const formatBinary = partial({base: 2, standard: "iec"});
formatBinary(1048576); // "1 MiB"

const formatBits = partial({bits: true});
formatBits(1024); // "8.19 kbit"
```

**See also:** filesize()

### Output Formats

[](#output-formats)

#### String Output (default)

[](#string-output-default)

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

#### Array Output

[](#array-output)

```
filesize(265318, {output: "array"}); // [265.32, "kB"]
filesize(1024, {output: "array", base: 2}); // [1, "KiB"]
```

#### Object Output

[](#object-output)

```
filesize(265318, {output: "object"});
// {value: 265.32, symbol: "kB", exponent: 1, unit: "kB"}
```

#### Exponent Output

[](#exponent-output)

```
filesize(1024, {output: "exponent"}); // 1
filesize(1048576, {output: "exponent", base: 2}); // 2
```

### Standards Support

[](#standards-support)

#### SI (International System of Units) - Default

[](#si-international-system-of-units---default)

```
filesize(1000); // "1 kB" (base 10)
filesize(1000000); // "1 MB"
```

#### IEC (International Electrotechnical Commission)

[](#iec-international-electrotechnical-commission)

```
filesize(1024, {standard: "iec", base: 2}); // "1 KiB"
filesize(1048576, {standard: "iec", base: 2}); // "1 MiB"
```

#### JEDEC (Joint Electron Device Engineering Council)

[](#jedec-joint-electron-device-engineering-council)

```
filesize(1024, {standard: "jedec"}); // "1 KB"
filesize(1048576, {standard: "jedec"}); // "1 MB"
```

Examples
--------

[](#examples)

### Basic Usage

[](#basic-usage)

```
import {filesize} from "filesize";

filesize(500); // "500 B"
filesize(1024); // "1.02 kB"
filesize(265318); // "265.32 kB"
filesize(265318, {round: 0}); // "265 kB"
```

### Binary Formats

[](#binary-formats)

```
// IEC binary prefixes (KiB, MiB, GiB)
filesize(1024, {base: 2, standard: "iec"}); // "1 KiB"
filesize(1048576, {base: 2, standard: "iec"}); // "1 MiB"

// JEDEC binary format (KB, MB, GB with binary calculation)
filesize(1024, {standard: "jedec"}); // "1 KB"
filesize(265318, {standard: "jedec"}); // "259.1 KB"
```

### Bits vs Bytes

[](#bits-vs-bytes)

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

### Custom Formatting

[](#custom-formatting)

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

// Custom separators and spacing
filesize(265318, {separator: ","}); // "265,32 kB"
filesize(265318, {spacer: ""}); // "265.32kB"

// Precision and padding
filesize(1536, {round: 3, pad: true}); // "1.536 kB"
filesize(1536, {precision: 3}); // "1.54 kB"
```

### Localization

[](#localization)

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

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

// Custom full forms
filesize(12, {fullform: true, fullforms: ["байтов"]}); // "12 байтов"
```

### Advanced Usage

[](#advanced-usage)

```
// Specific exponent
filesize(1024, {exponent: 0}); // "1024 B"
filesize(1024, {exponent: 1}); // "1.02 kB"

// BigInt support
filesize(BigInt(1024), {standard: "jedec"}); // "1 KB"

// Extreme precision for very large numbers
filesize(Math.pow(1024, 8), {precision: 3}); // "1.21 YB"
```

### Partial Application Patterns

[](#partial-application-patterns)

```
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(1048576); // "1 MiB"
formatBits(1024); // "8.19 kbit"
formatPrecise(1536); // "1.536 kB"
formatGerman(265318); // "265,32 kB"

// Method chaining equivalent
const sizes = [1024, 2048, 4096];
sizes.map(formatBinary); // ["1 KiB", "2 KiB", "4 KiB"]
```

Development
-----------

[](#development)

This project follows Node.js best practices and uses:

- **ES Modules** for modern JavaScript
- **Mocha** for testing with comprehensive coverage
- **ESLint** for code quality and consistency
- **Rollup** for building distributions
- **TypeScript definitions** for type safety

### Project Structure

[](#project-structure)

```
filesize.js/
├── src/
│   ├── filesize.js      # Main implementation
│   └── constants.js     # Unit definitions and constants
├── tests/
│   └── unit/
│       └── filesize.test.js  # Comprehensive test suite
├── types/
│   ├── filesize.d.ts    # TypeScript definitions
│   └── constants.d.ts   # Constants type definitions
└── package.json         # Dependencies and scripts

```

### Contributing

[](#contributing)

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Write tests for your changes
4. Ensure all tests pass (`npm test`)
5. Commit your changes (`git commit -m 'Add amazing feature'`)
6. Push to the branch (`git push origin feature/amazing-feature`)
7. Open a Pull Request

### Development Workflow

[](#development-workflow)

filesize.js includes an optimized development workflow with modern build tools:

- **🔄 Live Reload**: Use `npm run dev` for automatic rebuilds during development
- **📊 Bundle Analysis**: Monitor build sizes with `npm run build:analyze`
- **⚡ Fast Testing**: Live test running with `npm run test:watch`
- **🔧 Auto-fixing**: Automatic linting fixes with `npm run lint:fix`
- **📈 Performance**: Optimized Rollup configuration with enhanced tree shaking

**Build Output Analysis:**

- Minified ES Module: ~1.8KB (gzipped)
- UMD Bundle: ~1.9KB (gzipped)
- Comprehensive source maps included

### Development Commands

[](#development-commands)

```
# Install dependencies
npm install

# Development mode with live rebuild
npm run dev

# Build distribution
npm run build

# Build with bundle size analysis
npm run build:analyze

# Live rebuild during development
npm run build:watch

# Run linting
npm run lint

# Auto-fix linting issues
npm run lint:fix

# Run tests
npm test

# Live testing during development
npm run test:watch

# Run only unit tests
npm run mocha

# Bundle size analysis
npm run analyze:size

# Benchmarking
npm run benchmark
npm run benchmark:basic
npm run benchmark:stress
```

License
-------

[](#license)

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

###  Health Score

54

—

FairBetter than 97% of packages

Maintenance57

Moderate activity, may be stable

Popularity40

Moderate usage in the ecosystem

Community31

Small or concentrated contributor base

Maturity76

Established project with proven stability

 Bus Factor1

Top contributor holds 83.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~51 days

Recently: every ~132 days

Total

46

Last Release

1861d ago

Major Versions

3.6.1 → 4.0.02019-01-12

4.2.1 → 5.0.02019-10-01

5.0.3 → 6.0.02019-10-31

### Community

Maintainers

![](https://www.gravatar.com/avatar/c57b31c04075b96bd716ae6b0c43f874d8c67c088d0adf722ddec6feefa76508?d=identicon)[avoidwork](/maintainers/avoidwork)

---

Top Contributors

[![avoidwork](https://avatars.githubusercontent.com/u/369698?v=4)](https://github.com/avoidwork "avoidwork (419 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (48 commits)")[![realityking](https://avatars.githubusercontent.com/u/628508?v=4)](https://github.com/realityking "realityking (7 commits)")[![christopherscott](https://avatars.githubusercontent.com/u/125866?v=4)](https://github.com/christopherscott "christopherscott (3 commits)")[![tomoto](https://avatars.githubusercontent.com/u/552888?v=4)](https://github.com/tomoto "tomoto (2 commits)")[![getsnoopy](https://avatars.githubusercontent.com/u/2997884?v=4)](https://github.com/getsnoopy "getsnoopy (2 commits)")[![abaltuta](https://avatars.githubusercontent.com/u/37699890?v=4)](https://github.com/abaltuta "abaltuta (2 commits)")[![gitter-badger](https://avatars.githubusercontent.com/u/8518239?v=4)](https://github.com/gitter-badger "gitter-badger (1 commits)")[![gurpreetbaidwan](https://avatars.githubusercontent.com/u/4227224?v=4)](https://github.com/gurpreetbaidwan "gurpreetbaidwan (1 commits)")[![laughinghan](https://avatars.githubusercontent.com/u/225809?v=4)](https://github.com/laughinghan "laughinghan (1 commits)")[![litvinok](https://avatars.githubusercontent.com/u/1155664?v=4)](https://github.com/litvinok "litvinok (1 commits)")[![lngsx](https://avatars.githubusercontent.com/u/1572632?v=4)](https://github.com/lngsx "lngsx (1 commits)")[![pdehaan](https://avatars.githubusercontent.com/u/557895?v=4)](https://github.com/pdehaan "pdehaan (1 commits)")[![rnike](https://avatars.githubusercontent.com/u/48589760?v=4)](https://github.com/rnike "rnike (1 commits)")[![ryanramage](https://avatars.githubusercontent.com/u/795834?v=4)](https://github.com/ryanramage "ryanramage (1 commits)")[![ryanrhee](https://avatars.githubusercontent.com/u/242548?v=4)](https://github.com/ryanrhee "ryanrhee (1 commits)")[![starius](https://avatars.githubusercontent.com/u/920155?v=4)](https://github.com/starius "starius (1 commits)")[![tomoto-hitachi](https://avatars.githubusercontent.com/u/57977241?v=4)](https://github.com/tomoto-hitachi "tomoto-hitachi (1 commits)")[![vitormil](https://avatars.githubusercontent.com/u/391209?v=4)](https://github.com/vitormil "vitormil (1 commits)")[![wangxingkai](https://avatars.githubusercontent.com/u/6101654?v=4)](https://github.com/wangxingkai "wangxingkai (1 commits)")

---

Tags

bitsbytesfilefilesizefilesystemiecjedecsimplesizesize-calculationfilereadablefile systemsizefilesize

### Embed Badge

![Health badge](/badges/avoidwork-filesizejs/health.svg)

```
[![Health](https://phpackages.com/badges/avoidwork-filesizejs/health.svg)](https://phpackages.com/packages/avoidwork-filesizejs)
```

###  Alternatives

[league/flysystem

File storage abstraction for PHP

13.6k639.1M2.2k](/packages/league-flysystem)[league/flysystem-aws-s3-v3

AWS S3 filesystem adapter for Flysystem.

1.6k263.6M790](/packages/league-flysystem-aws-s3-v3)[knplabs/gaufrette

PHP library that provides a filesystem abstraction layer

2.5k39.8M123](/packages/knplabs-gaufrette)[knplabs/knp-gaufrette-bundle

Allows to easily use the Gaufrette library in a Symfony project

72428.6M91](/packages/knplabs-knp-gaufrette-bundle)[league/flysystem-local

Local filesystem adapter for Flysystem.

225231.8M39](/packages/league-flysystem-local)[league/flysystem-memory

In-memory filesystem adapter for Flysystem.

8533.6M194](/packages/league-flysystem-memory)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
