You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

blob.js 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. 'use strict'
  2. const Minipass = require('minipass')
  3. const TYPE = Symbol('type')
  4. const BUFFER = Symbol('buffer')
  5. class Blob {
  6. constructor (blobParts, options) {
  7. this[TYPE] = ''
  8. const buffers = []
  9. let size = 0
  10. if (blobParts) {
  11. const a = blobParts
  12. const length = Number(a.length)
  13. for (let i = 0; i < length; i++) {
  14. const element = a[i]
  15. const buffer = element instanceof Buffer ? element
  16. : ArrayBuffer.isView(element)
  17. ? Buffer.from(element.buffer, element.byteOffset, element.byteLength)
  18. : element instanceof ArrayBuffer ? Buffer.from(element)
  19. : element instanceof Blob ? element[BUFFER]
  20. : typeof element === 'string' ? Buffer.from(element)
  21. : Buffer.from(String(element))
  22. size += buffer.length
  23. buffers.push(buffer)
  24. }
  25. }
  26. this[BUFFER] = Buffer.concat(buffers, size)
  27. const type = options && options.type !== undefined
  28. && String(options.type).toLowerCase()
  29. if (type && !/[^\u0020-\u007E]/.test(type)) {
  30. this[TYPE] = type
  31. }
  32. }
  33. get size () {
  34. return this[BUFFER].length
  35. }
  36. get type () {
  37. return this[TYPE]
  38. }
  39. text () {
  40. return Promise.resolve(this[BUFFER].toString())
  41. }
  42. arrayBuffer () {
  43. const buf = this[BUFFER]
  44. const off = buf.byteOffset
  45. const len = buf.byteLength
  46. const ab = buf.buffer.slice(off, off + len)
  47. return Promise.resolve(ab)
  48. }
  49. stream () {
  50. return new Minipass().end(this[BUFFER])
  51. }
  52. slice (start, end, type) {
  53. const size = this.size
  54. const relativeStart = start === undefined ? 0
  55. : start < 0 ? Math.max(size + start, 0)
  56. : Math.min(start, size)
  57. const relativeEnd = end === undefined ? size
  58. : end < 0 ? Math.max(size + end, 0)
  59. : Math.min(end, size)
  60. const span = Math.max(relativeEnd - relativeStart, 0)
  61. const buffer = this[BUFFER]
  62. const slicedBuffer = buffer.slice(
  63. relativeStart,
  64. relativeStart + span
  65. )
  66. const blob = new Blob([], { type })
  67. blob[BUFFER] = slicedBuffer
  68. return blob
  69. }
  70. get [Symbol.toStringTag] () {
  71. return 'Blob'
  72. }
  73. static get BUFFER () {
  74. return BUFFER
  75. }
  76. }
  77. Object.defineProperties(Blob.prototype, {
  78. size: { enumerable: true },
  79. type: { enumerable: true },
  80. })
  81. module.exports = Blob