bom-handling.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. "use strict"
  2. var BOMChar = "\uFEFF"
  3. exports.PrependBOM = PrependBOMWrapper
  4. function PrependBOMWrapper (encoder, options) {
  5. this.encoder = encoder
  6. this.addBOM = true
  7. }
  8. PrependBOMWrapper.prototype.write = function (str) {
  9. if (this.addBOM) {
  10. str = BOMChar + str
  11. this.addBOM = false
  12. }
  13. return this.encoder.write(str)
  14. }
  15. PrependBOMWrapper.prototype.end = function () {
  16. return this.encoder.end()
  17. }
  18. // ------------------------------------------------------------------------------
  19. exports.StripBOM = StripBOMWrapper
  20. function StripBOMWrapper (decoder, options) {
  21. this.decoder = decoder
  22. this.pass = false
  23. this.options = options || {}
  24. }
  25. StripBOMWrapper.prototype.write = function (buf) {
  26. var res = this.decoder.write(buf)
  27. if (this.pass || !res) { return res }
  28. if (res[0] === BOMChar) {
  29. res = res.slice(1)
  30. if (typeof this.options.stripBOM === "function") { this.options.stripBOM() }
  31. }
  32. this.pass = true
  33. return res
  34. }
  35. StripBOMWrapper.prototype.end = function () {
  36. return this.decoder.end()
  37. }