Discover the Power of pretty-bytes for Effortless Byte Conversion

The pretty-bytes library is a powerful and user-friendly tool that converts numbers (representing bytes) into human-readable strings. Whether you are a developer working on data-intensive applications or a beginner exploring byte manipulation, pretty-bytes comes packed with APIs to simplify your tasks. This comprehensive guide explores its functionalities with dozens of practical examples and an impressive app implementation to maximize your understanding.

Getting Started

First, install the library using npm:

npm install pretty-bytes

Basic Usage

Converting bytes to a readable string is straightforward. Here’s a simple example:

const prettyBytes = require('pretty-bytes'); console.log(prettyBytes(1337)); // 1.34 kB

API Examples

1. Convert different byte values

console.log(prettyBytes(1000)); // 1 kB console.log(prettyBytes(1024)); // 1.02 kB console.log(prettyBytes(123456789)); // 123 MB

2. Specify number of decimal places

console.log(prettyBytes(123456, { maximumFractionDigits: 1 })); // 123.5 kB console.log(prettyBytes(123456, { maximumFractionDigits: 3 })); // 123.456 kB

3. Use locale settings

console.log(prettyBytes(1337, { locale: 'de' })); // 1,34 kB console.log(prettyBytes(1337, { locale: true })); // Locale of the user's environment

4. Binary and deci options

console.log(prettyBytes(1024, { binary: true })); // 1 KiB console.log(prettyBytes(1000, { binary: true })); // 1000 B

App Example

Here is a sample application that integrates several pretty-bytes APIs to demonstrate its versatility:

const prettyBytes = require('pretty-bytes');
// Sample data sizes in bytes const fileSizes = [1024, 5000000, 12345678, 987654, 5555];
// Function to print file sizes in a table function printFileSizes(sizes) {
  console.log('File Size Table:');
  console.log('----------------');
  sizes.forEach((size, index) => {
    console.log(`File ${index + 1}: ${prettyBytes(size, { maximumFractionDigits: 2, binary: true })}`);
  });
}
// Execute function printFileSizes(fileSizes); // Output: // File Size Table: // ---------------- // File 1: 1 KiB // File 2: 4.77 MiB // File 3: 11.77 MiB // File 4: 964 KiB // File 5: 5.42 KiB

This application iterates over an array of file sizes and prints each file size in a human-readable string using pretty-bytes with binary and decimal options.

Conclusion

The pretty-bytes library is a must-have for any JavaScript developer dealing with byte sizes. Its straightforward syntax and versatile options make byte conversion hassle-free. Try out these examples and incorporate pretty-bytes into your projects for more readable and user-friendly applications.

Hash: 4465e4c1554c572e2d636cb2ad7ef42997c4b6df480fb71d49b4cc31b61f7182

Leave a Reply

Your email address will not be published. Required fields are marked *