Bytes Utility for Node.js

3.1.2 · active · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

Demonstrates parsing byte strings to numbers, formatting numbers to byte strings, and using specific `format` and `parse` functions with various options and error handling.

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

view raw JSON →