Converting file size in bytes to human-readable string

后端 未结 19 1694
眼角桃花
眼角桃花 2020-11-28 17:58

I\'m using this function to convert a file size in bytes to a human-readable file size:

function getReadableFileSizeString(fileSizeInBytes) {
    var i = -1;         


        
相关标签:
19条回答
  • 2020-11-28 18:42

    I found @cocco's answer interesting, but had the following issues with it:

    1. Don't modify native types or types you don't own
    2. Write clean, readable code for humans, let minifiers optimize code for machines
    3. (Bonus for TypeScript users) Doesn't play well with TypeScript

    TypeScript:

     /**
     * Describes manner by which a quantity of bytes will be formatted.
     */
    enum ByteFormat {
      /**
       * Use Base 10 (1 kB = 1000 bytes). Recommended for sizes of files on disk, disk sizes, bandwidth.
       */
      SI = 0,
      /**
       * Use Base 2 (1 KiB = 1024 bytes). Recommended for RAM size, size of files on disk.
       */
      IEC = 1
    }
    
    /**
     * Returns a human-readable representation of a quantity of bytes in the most reasonable unit of magnitude.
     * @example
     * formatBytes(0) // returns "0 bytes"
     * formatBytes(1) // returns "1 byte"
     * formatBytes(1024, ByteFormat.IEC) // returns "1 KiB"
     * formatBytes(1024, ByteFormat.SI) // returns "1.02 kB"
     * @param size The size in bytes.
     * @param format Format using SI (Base 10) or IEC (Base 2). Defaults to SI.
     * @returns A string describing the bytes in the most reasonable unit of magnitude.
     */
    function formatBytes(
      value: number,
      format: ByteFormat = ByteFormat.SI
    ) {
      const [multiple, k, suffix] = (format === ByteFormat.SI
        ? [1000, 'k', 'B']
        : [1024, 'K', 'iB']) as [number, string, string]
      // tslint:disable-next-line: no-bitwise
      const exp = (Math.log(value) / Math.log(multiple)) | 0
      // or, if you'd prefer not to use bitwise expressions or disabling tslint rules, remove the line above and use the following:
      // const exp = value === 0 ? 0 : Math.floor(Math.log(value) / Math.log(multiple)) 
      const size = Number((value / Math.pow(multiple, exp)).toFixed(2))
      return (
        size +
        ' ' +
        (exp 
           ? (k + 'MGTPEZY')[exp - 1] + suffix 
           : 'byte' + (size !== 1 ? 's' : ''))
      )
    }
    
    // example
    [0, 1, 1024, Math.pow(1024, 2), Math.floor(Math.pow(1024, 2) * 2.34), Math.pow(1024, 3), Math.floor(Math.pow(1024, 3) * 892.2)].forEach(size => {
      console.log('Bytes: ' + size)
      console.log('SI size: ' + formatBytes(size))
      console.log('IEC size: ' + formatBytes(size, 1) + '\n')
    });
    
    0 讨论(0)
提交回复
热议问题