binary.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { Scalar } from '../../nodes/Scalar.js';
  2. import { stringifyString } from '../../stringify/stringifyString.js';
  3. const binary = {
  4. identify: value => value instanceof Uint8Array, // Buffer inherits from Uint8Array
  5. default: false,
  6. tag: 'tag:yaml.org,2002:binary',
  7. /**
  8. * Returns a Buffer in node and an Uint8Array in browsers
  9. *
  10. * To use the resulting buffer as an image, you'll want to do something like:
  11. *
  12. * const blob = new Blob([buffer], { type: 'image/jpeg' })
  13. * document.querySelector('#photo').src = URL.createObjectURL(blob)
  14. */
  15. resolve(src, onError) {
  16. if (typeof Buffer === 'function') {
  17. return Buffer.from(src, 'base64');
  18. }
  19. else if (typeof atob === 'function') {
  20. // On IE 11, atob() can't handle newlines
  21. const str = atob(src.replace(/[\n\r]/g, ''));
  22. const buffer = new Uint8Array(str.length);
  23. for (let i = 0; i < str.length; ++i)
  24. buffer[i] = str.charCodeAt(i);
  25. return buffer;
  26. }
  27. else {
  28. onError('This environment does not support reading binary tags; either Buffer or atob is required');
  29. return src;
  30. }
  31. },
  32. stringify({ comment, type, value }, ctx, onComment, onChompKeep) {
  33. const buf = value; // checked earlier by binary.identify()
  34. let str;
  35. if (typeof Buffer === 'function') {
  36. str =
  37. buf instanceof Buffer
  38. ? buf.toString('base64')
  39. : Buffer.from(buf.buffer).toString('base64');
  40. }
  41. else if (typeof btoa === 'function') {
  42. let s = '';
  43. for (let i = 0; i < buf.length; ++i)
  44. s += String.fromCharCode(buf[i]);
  45. str = btoa(s);
  46. }
  47. else {
  48. throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');
  49. }
  50. if (!type)
  51. type = Scalar.BLOCK_LITERAL;
  52. if (type !== Scalar.QUOTE_DOUBLE) {
  53. const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
  54. const n = Math.ceil(str.length / lineWidth);
  55. const lines = new Array(n);
  56. for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {
  57. lines[i] = str.substr(o, lineWidth);
  58. }
  59. str = lines.join(type === Scalar.BLOCK_LITERAL ? '\n' : ' ');
  60. }
  61. return stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
  62. }
  63. };
  64. export { binary };