index.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. const PassThroughDecoder = require('./lib/pass-through-decoder')
  2. const UTF8Decoder = require('./lib/utf8-decoder')
  3. module.exports = class TextDecoder {
  4. constructor (encoding = 'utf8') {
  5. this.encoding = normalizeEncoding(encoding)
  6. switch (this.encoding) {
  7. case 'utf8':
  8. this.decoder = new UTF8Decoder()
  9. break
  10. case 'utf16le':
  11. case 'base64':
  12. throw new Error('Unsupported encoding: ' + this.encoding)
  13. default:
  14. this.decoder = new PassThroughDecoder(this.encoding)
  15. }
  16. }
  17. get remaining () {
  18. return this.decoder.remaining
  19. }
  20. push (data) {
  21. if (typeof data === 'string') return data
  22. return this.decoder.decode(data)
  23. }
  24. // For Node.js compatibility
  25. write (data) {
  26. return this.push(data)
  27. }
  28. end (data) {
  29. let result = ''
  30. if (data) result = this.push(data)
  31. result += this.decoder.flush()
  32. return result
  33. }
  34. }
  35. function normalizeEncoding (encoding) {
  36. encoding = encoding.toLowerCase()
  37. switch (encoding) {
  38. case 'utf8':
  39. case 'utf-8':
  40. return 'utf8'
  41. case 'ucs2':
  42. case 'ucs-2':
  43. case 'utf16le':
  44. case 'utf-16le':
  45. return 'utf16le'
  46. case 'latin1':
  47. case 'binary':
  48. return 'latin1'
  49. case 'base64':
  50. case 'ascii':
  51. case 'hex':
  52. return encoding
  53. default:
  54. throw new Error('Unknown encoding: ' + encoding)
  55. }
  56. };