Giter Site home page Giter Site logo

pretty-bytes's Introduction

pretty-bytes

Convert bytes to a human readable string: 13371.34 kB

Useful for displaying file sizes for humans.

Note that it uses base-10 (e.g. kilobyte). Read about the difference between kilobyte and kibibyte.

Install

npm install pretty-bytes

Usage

import prettyBytes from 'pretty-bytes';

prettyBytes(1337);
//=> '1.34 kB'

prettyBytes(100);
//=> '100 B'

// Display with units of bits
prettyBytes(1337, {bits: true});
//=> '1.34 kbit'

// Display file size differences
prettyBytes(42, {signed: true});
//=> '+42 B'

// Localized output using German locale
prettyBytes(1337, {locale: 'de'});
//=> '1,34 kB'

API

prettyBytes(number, options?)

number

Type: number

The number to format.

options

Type: object

signed

Type: boolean
Default: false

Include plus sign for positive numbers. If the difference is exactly zero a space character will be prepended instead for better alignment.

bits

Type: boolean
Default: false

Format the number as bits instead of bytes. This can be useful when, for example, referring to bit rate.

binary

Type: boolean
Default: false

Format the number using the Binary Prefix instead of the SI Prefix. This can be useful for presenting memory amounts. However, this should not be used for presenting file sizes.

locale

Type: boolean | string
Default: false (No localization)

Important: Only the number and decimal separator are localized. The unit title is not and will not be localized.

  • If true: Localize the output using the system/browser locale.
  • If string: Expects a BCP 47 language tag (For example: en, de, …)
  • If string[]: Expects a list of BCP 47 language tags (For example: en, de, …)
minimumFractionDigits

Type: number
Default: undefined

The minimum number of fraction digits to display.

If neither minimumFractionDigits or maximumFractionDigits are set, the default behavior is to round to 3 significant digits.

import prettyBytes from 'pretty-bytes';

// Show the number with at least 3 fractional digits
prettyBytes(1900, {minimumFractionDigits: 3});
//=> '1.900 kB'

prettyBytes(1900);
//=> '1.9 kB'
maximumFractionDigits

Type: number
Default: undefined

The maximum number of fraction digits to display.

If neither minimumFractionDigits or maximumFractionDigits are set, the default behavior is to round to 3 significant digits.

import prettyBytes from 'pretty-bytes';

// Show the number with at most 1 fractional digit
prettyBytes(1920, {maximumFractionDigits: 1});
//=> '1.9 kB'

prettyBytes(1920);
//=> '1.92 kB'
space

Type: boolean
Default: true

Put a space between the number and unit.

import prettyBytes from 'pretty-bytes';

prettyBytes(1920, {space: false});
//=> '1.9kB'

prettyBytes(1920);
//=> '1.92 kB'

Related

pretty-bytes's People

Contributors

battaglr avatar bendingbender avatar caub avatar dawsbot avatar ivankravets avatar jakecastelli avatar kevva avatar klevente avatar meisterlampe avatar nminhnguyen avatar nmoinvaz avatar patrickkettner avatar siilwyn avatar sindresorhus avatar turbo87 avatar yciabaud avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pretty-bytes's Issues

Throws for BigInt

The function Number.isFinite returns false for all arguments of type bigint. So the formatting function throws immediately. It would be helpful if bigint would be supported as well. I would like to use it with Node's fs.stat, which now can return bigint values for file sizes.

(I tested how the function would behave without the check, and unfortunately the Math functions do not support bigint arguments: Cannot convert a BigInt value to a number at Math.log)

Support ES5

Recreating #42 because your continued response to this request leaves a lot to be desired.

Can you at least put a giant warning on your README that says "Don't use this in a browser if you want to support IE 11"?

You're wasting a lot of people's time debugging code that explodes on IE 11. And in IE11 when using webpack, the error messages are basically worthless.

To everyone else. I'll work on forking it and making an ES5 version.

Unexpected token: operator (>)

With webpack i'm getting the following error:

ERROR in app.aa267055ad0890445649.js from UglifyJs
SyntaxError: Unexpected token: operator (>) [./~/pretty-bytes/index.js:4,0]

Does this library have to use es6? Doesn't seem like its essential.

Do the viceversa

Any module that does the viceversa?
Like:

toBytes('1MB') // 1048576

IE 11 support

IE 11 throws an error when i package this with webpack and vue.

Error : SCRIPT1002 : SYNTAX ERROR
Chunk-vendors.js

When i dive in to chunk vendors, the line that gets highlighted is

'eval("\n\nconst BYTE_UNITS = [\n\t'B',\n\t'kB',\n\t'MB',\n\t'GB',\n\t'TB',\n\t'PB',\n\t'EB',\n\t'ZB',\n\t'YB'\n];\n\nconst BIT_UNITS = [\n\t'b',\n\t'kbit',\n\t'Mbit',\n\t'Gbit',\n\t'Tbit',\n\t'Pbit',\n\t'Ebit',\n\t'Zbit',\n\t'Ybit'\n];\n\n/*\nFormats the given number using Number#toLocaleString.\n- If locale is a string, the value is expected to be a locale-key (for example: de).\n- If locale is true, the system default locale is used for '

Do i need to run this through babel ? What are the polyfills needed so i can include them in my transpileDependices.

Thanks.

need to use arrow function and template strings? webpack uglifyjs errors with default options.

My bundle size shot up after using this library, and after some digging, I discovered that UglifyJS runs into errors without more configuration, which could be solved if we weren't using advanced es6 (ES2015) features like arrow function and template strings.

replacing 4 lines with:

module.exports = function(num) {
	if (!Number.isFinite(num)) {
		throw new TypeError('Expected a finite number, got ' + (typeof num) + ': ' + num);
	}

fixes the issue and seems easy enough. My alternative is to try to figure out how to get UglifyJS to do what I want, or use a different library, and using a different library is easier for me. I just felt like saving people some time and making this library easier to consume. No need to not support older JavaScript programs for such a small library function right?

Provide a index.js5

So I love Ecmascript 2015, and the fact support for it is growing:
http://kangax.github.io/compat-table/es6/

Cool that node 4 supports it. 👍

However there are a lot of javascript out there not running on node 4.
For example I'm working with Enonic XP https://enonic.com/ (my employer) which is using http://purplejs.io/ which runs on Java JVMs Nashhorn

And it seems Nashhorn wont support ES2015 before JDK9
http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/

So perhaps instead of removing ES2015, or renaming index.js to index.es6, could you provide a transpiled index.js5 file?

(Side note: My babel didn't transpile Number.isFinite, perhaps I must update babel or configure it)

Similar issues:

Remove es6
#26

UglifyJS can't parse [email protected] without transpilation
#22

prettyBytes(0.5) -> "500 undefined"

Even though 0.5 bytes doesn't make a lot of sense (probably depends on file system), but inputting 0.5 bytes will result in 500 undefined.

A possible solution is to check is to check for a fraction and then perhaps Math.round() it.

Document es2015 usage

Hey there. Just went through setting up this lib and hit es2015 issues like others have in the past. To fix it, I simply downgraded.

I was wondering if you would be open to a PR that updates the readme to include a little blurb about that. Might help prevent more open issues related to this in the future but I can see why you might feel that having that documented isn't required.

Make it prettier? 26.2MB => 25MB

node -i
> require('bytes')('25mb')
26214400
> require('bytes')(26214400)
'25MB'
> require('pretty-bytes')(26214400)
'26.2 MB'

I'd like pretty-bytes to be pretty and output 25 instead of 26.2, maybe we can add a boolean second argument for this?

Non-pretty results on these numbers

var fn = require('./')
console.log(fn(0.8888888888888)) // 0.8888888888888 B
console.log(fn(-0.578234243)) // -0.578234243 B

Would you accept a PR to fix this?

Fixed width format

For progress bars, it would be nice to have an output format that is always the same width. E.g. a possible six character wide format:

            1 -> 0.0 kB
           10 -> 0.0 kB
          100 -> 0.1 kB
         1000 -> 1.0 kB
        10000 ->  10 kB
       100000 -> 100 kB
      1000000 -> 1.0 MB
     10000000 ->  10 MB
    100000000 -> 100 MB
   1000000000 -> 1.0 GB
  10000000000 ->  10 GB
 100000000000 -> 100 GB
1000000000000 -> 1.0 TB

Rounding bug between 1001 and 1023 in binary mode

There seems to be a rounding bug when using the binary option:

Input Actual output Expected output
1001 1000 B 1001 B
1023 1020 B 1023 B
1037263 1010 KiB 1013 KiB
1051013543 1000 MiB 1002 MiB
1054331017 1010 MiB 1005 MiB

Code:
prettyBytes(input, {binary: true})

It appears that the number is rounded to a multiple of ten.
It looks like this only happens for outputs between 1001 and 1023 (inclusive).

Add warning about 3.x removing the CLI?

I cringe when I see these -cli repos come trickle into my Github feed, but I understand the logic and can appreciate the need to isolate dependencies.

When this happened with gzip-size all my projects broke after updating - and that's fine since it was a major version change - but there was very little in the way of a "hey, you're trying to invoke a non-CLI module now". It might be worth warning people - semver helps and all, but lots of people use hacky stuff like npm-check-updates -u without realizing what they are doing.

Even something like retaining a bin/pretty-bytes that just prints a removal notice would be nice.

Separate CLI into its own module

The meow and get-stdin modules are only necessary for usage as a CLI, but are installed even if this module is only used as a function in an application. Could this be separated into a different level?

pretty-bytes is converting what apple shows as 1mb to 1.05mb in code

On macOS Montery version 12.6.1, when I go to upload a 1mb file - it shows on mac as 1mb, however, when uploading the file and converting it with prettyBytes it shows as 1.05mb because we are using the File.prototype.size to convert the file size to bytes. Why are they different?. Does apple round down or something? Also, when using the prettyBytes to convert the max file size, which we have as 1000000 bytes - it correctly shows up with the conversion with prettyBytes as 1mb.

Screen Shot 2022-12-16 at 3 40 51 PM

Screen Shot 2022-12-16 at 3 58 35 PM

Screen Shot 2022-12-16 at 3 41 17 PM

Screen Shot 2022-12-16 at 3 48 57 PM

File =
1.txt

Use Number.toPrecision(3) instead of Number.toFixed(2)

I'm suggesting switching to Number.toPrecision(3) instead of Number.toFixed(2).

value toFixed(2) toPrecision(3)
123.4 123.40 123
12.34 12.34 12.3
1.234 1.23 1.23
123 123.00 123
1234 1234.00 1.23e+3

The last case is probably not desirable, but shouldn't happen if value < 999.5.

What do you think? Should I send a PR?

Use of const in strict mode

With latest versions of pretty-bytes, i have this error :

SyntaxError: /space/node_modules/grunt-pngquant/node_modules/pretty-bytes/index.js:2
const UNITS = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
^^^^^
Use of const in strict mode.

I'm using nodejs 4.5.0.
Can you fix this problem ?

Invalid configuration reported

I am getting this error when bundling my app

Package pretty-bytes has been ignored because it contains invalid configuration. 
Reason: Package subpath './package.json' is not defined by "exports" in /.../app/node_modules/pretty-bytes/package.json

Not sure if its related to this library or my project setup?

Publish pre-compiled version of pretty-bytes

From https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#npm-run-build-fails-to-minify

To resolve this:
Open an issue on the dependency's issue tracker and ask that the package be published pre-compiled.

I got this error message when trying to build my app using react-scripts:

Creating an optimized production build...
Failed to compile.

Failed to minify the code from this file:

 	./node_modules/pretty-bytes/index.js:4

Read more here: http://bit.ly/2tRViJ9

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

UglifyJS can't parse [email protected] without transpilation

I use webpack + babel-loader, and got errors when build production code, where you use arrow functions and template literals.

With general webpack configuration, webpack users usually don't load modules from node_modules to babel-loader. I think you should avoid using those syntax. I'm happy to create a PR.

Locale-aware decimal seperator

As you may or may not know, 24% of the world uses , as the decimal separator, and I'd like to see an option to make pretty-bytes locale-aware.

Number.protype.toFixed isn't locale-aware and always outputs a . seperator. A possible replacement could be Number.prototype.toLocaleString:

num.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })

This API is pretty recent and doesn't work on node yet, so for I guess another solution is needed.

Byte units are not translated

In France, we don't say bytes but octets. Thus, we don't use the B short name as in 42 MB but o as in 42 Mo.

As pretty-bytes already have a locale option, it can be seen as a defect since the resulting string is partially localized (only the floating point is being localized).

Example

English Expected FR Actual FR
32.5 B 32,5 o 32,5 B
12.3 kB 12,3 ko 12,3 kB

maximumFractionDigits not working as expected

This code

console.log({
    size,
    def: prettyBytes(size),
    max: prettyBytes(size, { maximumFractionDigits: 1 }),
    minMax: prettyBytes(size, {
      maximumFractionDigits: 1,
      minimumFractionDigits: 1,
    }),
  });

Results in following output:

{"def": "60 MB", "max": "59.952784 MB", "minMax": "59.952784 MB", "size": 59952784}

I expect that both max and minMax should be 59.9 MB.

I'm using pretty-bytes@^5.6.0

New option for precision

Would be good to have an option to allow one digit after the floating-point.

Especially for scientific based apps.

Remove es6

This module uses const, depending on someones build process, they may or may not run node modules through a transpiler - which is why most npm modules include a built or just write it in es5 compliant javascript outright

Handle values higher than 1000 YB

Not sure it's usefulness, but you never know. Right now it returns undefined. It should rather just keep YB and up the number itself.

❯ pretty-bytes 23124325643576321123445664321
23.12 undefined

Publish the code as ES5 ?

I am using the pretty-bytes package in a frontend reactjs application (using create-react-app for building)
I just got this error when doing "npm run build" on my application:

Creating an optimized production build...
Failed to compile.

Failed to minify the code from this file: 

        ./node_modules/pretty-bytes/index.js:4 

Read more here: http://bit.ly/2tRViJ9

Would it be possible to publish this great pretty-bytes code on NPM with the ES5 syntaxe?

Specify if use a extra space

What's do you think about this:

prettyBytes(1337);
//=> '1.34 kB'
prettyBytes(1337, { space: false });
//=> '1.34kB'

Should not distribute ES6

Its bad form to distribute an ES6 package that does not specifically target "modules" or such in package.json. Assumptions are as a standard - code will be compliant with current standards

Module parse failed: Unexpected token (74:2)

react, dva project,npm run start will be Error

./node_modules/pretty-bytes/index.js
Module parse failed: Unexpected token (74:2)
You may need an appropriate loader to handle this file type.
image

function as => retrive error in IE

I use angular-cli 1.5.6 and i did the imports of ES6 the polyfills for Internet Explorer.

import 'core-js/es6/symbol'; import 'core-js/es6/object'; import 'core-js/es6/function'; import 'core-js/es6/parse-import import 'core-js/es6/parse-float'; import 'core-js/es6/number'; import 'core-js/es6/math'; import 'core-js/es6/string'; import 'core-js/es6/date'; import 'core-js/es6/array'; import 'core-js/es6/regexp'; import 'core-js/es6/map'; import 'core-js/es6/weak-map'; import 'core-js/es6/set';
But, i still get the IE Error:
SCRIPT1002 syntax error. in IE 11.

The error is related to the arrow symbol, i change the code num => for function(num) and works fine.

What polyfill i missed?
May be is necessary keep compatibility with ES5?

What do you recommend?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.