binary.js 2.6 KB

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