龙空技术网

前端库推荐: byte-size 计算字节大小KB,MB,GB,TB,PB,EB,ZB

一度开外 25

前言:

此时小伙伴们对“js判断字符串的字节长度”大约比较讲究,兄弟们都需要剖析一些“js判断字符串的字节长度”的相关文章。那么小编同时在网络上网罗了一些对于“js判断字符串的字节长度””的相关知识,希望同学们能喜欢,小伙伴们一起来学习一下吧!

今天的库明星是 byte-size,用来计算及表达字节大小。

网址:

Value

Metric

Metric (octet)

1000

kB kilobyte

ko kilooctet

1000^2

MB megabyte

Mo megaoctet

1000^3

GB gigabyte

Go gigaoctet

1000^4

TB terabyte

To teraoctet

1000^5

PB petabyte

Po petaoctet

1000^6

EB exabyte

Eo exaoctet

1000^7

ZB zettabyte

Zo zettaoctet

1000^8

YB yottabyte

Yo yottaoctet

设置示例:

Synopsis

By default, byteSize converts the input number to a human readable string with metric units and a precision of 1.

> const byteSize = require('byte-size')> byteSize(1580){ value: '1.6', unit: 'kB', long: 'kilobytes' }

The object returned by byteSize defines a toString method therefore can be used directly in string context.

> `Filesize: ${byteSize(12400)}`'Filesize: 12.4 kB'

Override the default toString behaviour by setting options.toStringFn.

> function toStringFn () {  return `**${this.value}${this.unit}**`}> `Filesize: ${byteSize(12400, { toStringFn })}`'Filesize: **12.4kB**'

Beside the default of metric, there are three other built-in units available: metric_octet, iec and iec_octet.

> byteSize(1580, { units: 'iec' }){ value: '1.5', unit: 'KiB', long: 'kibibytes' }> byteSize(1580, { units: 'iec_octet' }){ value: '1.5', unit: 'Kio', long: 'kibioctets' }> byteSize(1580, { units: 'metric_octet' }){ value: '1.6', unit: 'ko', long: 'kilooctets' }

You can adjust the precision.

> byteSize(1580, { units: 'iec', precision: 3 }){ value: '1.543', unit: 'KiB', long: 'kibibytes' }> byteSize(1580, { units: 'iec', precision: 0 }){ value: '2', unit: 'KiB', long: 'kibibytes' }

Define custom units by passing an object containing one or more additional conversion tables to options.customUnits. In options.units, specify the name of a property from the customUnits object.

> const customUnits = {  simple: [    { from: 0   , to: 1e3 , unit: ''  },    { from: 1e3 , to: 1e6 , unit: 'K', long: 'thousand' },    { from: 1e6 , to: 1e9 , unit: 'Mn', long: 'million' },    { from: 1e9 , to: 1e12, unit: 'Bn', long: 'billion' }  ]}> const { value, unit } = byteSize(10000, { customUnits, units: 'simple' })> `${value}${unit}`'10.0K'

Override the built-in defaults for the duration of the process by passing an options object to byteSize.defaultOptions(). This results in cleaner code in cases where byteSize is used often with the same options.

> byteSize.defaultOptions({  units: 'simple',  precision: 2,  customUnits: {    simple: [      { from: 0, to: 1e3, unit: '' },      { from: 1e3, to: 1e6, unit: 'k' },      { from: 1e6, to: 1e9, unit: 'm' },      { from: 1e9, to: 1e12, unit: 'bn' },    ]  },  toStringFn: function () {    return this.value + this.unit  }})> [2400, 16400, 3991200].map(byteSize).join(', ')'2.40k, 16.40k, 3.99m'

标签: #js判断字符串的字节长度