ParseFileEncode.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. function b64Digit(number) {
  2. if (number < 26) {
  3. return String.fromCharCode(65 + number);
  4. }
  5. if (number < 52) {
  6. return String.fromCharCode(97 + (number - 26));
  7. }
  8. if (number < 62) {
  9. return String.fromCharCode(48 + (number - 52));
  10. }
  11. if (number === 62) {
  12. return '+';
  13. }
  14. if (number === 63) {
  15. return '/';
  16. }
  17. throw new TypeError("Tried to encode large digit " + number + " in base64.");
  18. }
  19. function encodeBase64(bytes) {
  20. var chunks = [];
  21. chunks.length = Math.ceil(bytes.length / 3);
  22. for (var i = 0; i < chunks.length; i++) {
  23. var b1 = bytes[i * 3];
  24. var b2 = bytes[i * 3 + 1] || 0;
  25. var b3 = bytes[i * 3 + 2] || 0;
  26. var has2 = i * 3 + 1 < bytes.length;
  27. var has3 = i * 3 + 2 < bytes.length;
  28. chunks[i] = [b64Digit(b1 >> 2 & 0x3f), b64Digit(b1 << 4 & 0x30 | b2 >> 4 & 0x0f), has2 ? b64Digit(b2 << 2 & 0x3c | b3 >> 6 & 0x03) : '=', has3 ? b64Digit(b3 & 0x3f) : '='].join('');
  29. }
  30. return chunks.join('');
  31. }
  32. module.exports = {
  33. encodeBase64: encodeBase64,
  34. b64Digit: b64Digit
  35. };