Node-Red configuration
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

encodePacket.browser.js 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { PACKET_TYPES } from "./commons.js";
  2. const withNativeBlob = typeof Blob === "function" ||
  3. (typeof Blob !== "undefined" &&
  4. Object.prototype.toString.call(Blob) === "[object BlobConstructor]");
  5. const withNativeArrayBuffer = typeof ArrayBuffer === "function";
  6. // ArrayBuffer.isView method is not defined in IE10
  7. const isView = (obj) => {
  8. return typeof ArrayBuffer.isView === "function"
  9. ? ArrayBuffer.isView(obj)
  10. : obj && obj.buffer instanceof ArrayBuffer;
  11. };
  12. const encodePacket = ({ type, data }, supportsBinary, callback) => {
  13. if (withNativeBlob && data instanceof Blob) {
  14. if (supportsBinary) {
  15. return callback(data);
  16. }
  17. else {
  18. return encodeBlobAsBase64(data, callback);
  19. }
  20. }
  21. else if (withNativeArrayBuffer &&
  22. (data instanceof ArrayBuffer || isView(data))) {
  23. if (supportsBinary) {
  24. return callback(data);
  25. }
  26. else {
  27. return encodeBlobAsBase64(new Blob([data]), callback);
  28. }
  29. }
  30. // plain string
  31. return callback(PACKET_TYPES[type] + (data || ""));
  32. };
  33. const encodeBlobAsBase64 = (data, callback) => {
  34. const fileReader = new FileReader();
  35. fileReader.onload = function () {
  36. const content = fileReader.result.split(",")[1];
  37. callback("b" + (content || ""));
  38. };
  39. return fileReader.readAsDataURL(data);
  40. };
  41. function toArray(data) {
  42. if (data instanceof Uint8Array) {
  43. return data;
  44. }
  45. else if (data instanceof ArrayBuffer) {
  46. return new Uint8Array(data);
  47. }
  48. else {
  49. return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  50. }
  51. }
  52. let TEXT_ENCODER;
  53. export function encodePacketToBinary(packet, callback) {
  54. if (withNativeBlob && packet.data instanceof Blob) {
  55. return packet.data.arrayBuffer().then(toArray).then(callback);
  56. }
  57. else if (withNativeArrayBuffer &&
  58. (packet.data instanceof ArrayBuffer || isView(packet.data))) {
  59. return callback(toArray(packet.data));
  60. }
  61. encodePacket(packet, false, (encoded) => {
  62. if (!TEXT_ENCODER) {
  63. TEXT_ENCODER = new TextEncoder();
  64. }
  65. callback(TEXT_ENCODER.encode(encoded));
  66. });
  67. }
  68. export { encodePacket };