Bytes Utility for Node.js
The `bytes` package (current stable version 3.1.2) is a focused JavaScript utility designed for converting human-readable byte strings (e.g., "1KB", "5.5GB") into their numerical byte equivalents, and vice-versa. It provides a simple, unified API that delegates to a `format` function for converting numbers to strings and a `parse` function for converting strings or numbers to bytes. A key differentiator is its strict adherence to powers of two for unit conversions (e.g., 1KB equals 1024 bytes), which is critical for accurate storage and memory calculations, distinguishing it from decimal-based systems. While major releases are not frequent, the library is stable and widely used, typically receiving updates for bug fixes or minor enhancements. It supports various units including B, KB, MB, GB, TB, and PB, and offers formatting options such as decimal places, thousands separators, and custom unit separators.
Common errors
-
TypeError: bytes is not a function
cause Attempting to call `bytes` as a function after an incorrect named import in ESM, or if the `require` result was not the function itself.fixEnsure you are importing the default export correctly: `import bytes from 'bytes';` (ESM) or `const bytes = require('bytes');` (CommonJS). -
ReferenceError: require is not defined
cause Using `require()` in a modern ES module environment without appropriate Babel or TypeScript configuration, or without setting `"type": "commonjs"` in `package.json`.fixFor ESM projects, use `import bytes from 'bytes';`. If you must use `require` in an ESM file, consider converting the file to CommonJS or using a build tool that handles CJS-ESM interoperability. -
TypeError: Cannot read properties of undefined (reading 'format')
cause This usually occurs when `bytes` itself is `undefined` because of a failed or incorrect import, meaning `bytes.format` cannot be accessed.fixVerify that `import bytes from 'bytes';` or `const bytes = require('bytes');` correctly assigns the module to the `bytes` variable before attempting to call its properties like `format` or `parse`.
Warnings
- gotcha The `bytes` utility strictly uses powers of two (1024) for unit conversions (e.g., 1KB = 1024B, 1MB = 1024KB). This is crucial for storage and memory contexts but differs from decimal (1000) systems often seen in networking or marketing.
- gotcha The `bytes()` function (and `bytes.parse()`, `bytes.format()`) returns `null` for invalid input instead of throwing an error. Developers must explicitly check for `null` to handle parsing or formatting failures gracefully.
- breaking In version 3.0.0, the `bytes.format()` method no longer accepts 'b' as a specific unit in the `unit` option. It now auto-detects the most appropriate unit. To format a value strictly in bytes, ensure `unit` is not set or the value is small enough to naturally format as bytes.
Install
-
npm install bytes -
yarn add bytes -
pnpm add bytes
Imports
- bytes
import { bytes } from 'bytes';import bytes from 'bytes';
- bytes.format
import { format } from 'bytes'; const formatted = format(1024);import bytes from 'bytes'; const formatted = bytes.format(1024);
- bytes.parse
const { parse } = require('bytes'); const parsed = parse('1KB');const bytes = require('bytes'); const parsed = bytes.parse('1KB');
Quickstart
import bytes from 'bytes';
// Parse a human-readable string to its byte equivalent
const oneKilobyte = bytes('1KB');
console.log(`'1KB' parses to: ${oneKilobyte} bytes`); // Expected: 1024
// Format a number of bytes into a human-readable string
const formattedMegaBytes = bytes(1024 * 1024 * 5.5);
console.log(`5.5MB (raw bytes) formats to: ${formattedMegaBytes}`); // Expected: '5.5MB'
// Using bytes.format with options
const bigNumber = 1000 * 1000 * 1000 * 1.2345;
const formattedWithDecimal = bytes.format(bigNumber, { decimalPlaces: 3, unit: 'GB', unitSeparator: ' ' });
console.log(`1.2345GB with options: ${formattedWithDecimal}`); // Expected: '1.235 GB'
// Using bytes.parse directly
const twoPetabytes = bytes.parse('2PB');
console.log(`'2PB' parses to: ${twoPetabytes} bytes`);
// Handling invalid input
const invalidParse = bytes.parse('not a byte string');
console.log(`Parsing invalid string returns: ${invalidParse}`); // Expected: null