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.js 1.2KB

123456789101112131415161718192021222324252627282930313233
  1. import { PACKET_TYPES } from "./commons.js";
  2. export const encodePacket = ({ type, data }, supportsBinary, callback) => {
  3. if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
  4. return callback(supportsBinary ? data : "b" + toBuffer(data, true).toString("base64"));
  5. }
  6. // plain string
  7. return callback(PACKET_TYPES[type] + (data || ""));
  8. };
  9. const toBuffer = (data, forceBufferConversion) => {
  10. if (Buffer.isBuffer(data) ||
  11. (data instanceof Uint8Array && !forceBufferConversion)) {
  12. return data;
  13. }
  14. else if (data instanceof ArrayBuffer) {
  15. return Buffer.from(data);
  16. }
  17. else {
  18. return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
  19. }
  20. };
  21. let TEXT_ENCODER;
  22. export function encodePacketToBinary(packet, callback) {
  23. if (packet.data instanceof ArrayBuffer || ArrayBuffer.isView(packet.data)) {
  24. return callback(toBuffer(packet.data, false));
  25. }
  26. encodePacket(packet, true, (encoded) => {
  27. if (!TEXT_ENCODER) {
  28. // lazily created for compatibility with Node.js 10
  29. TEXT_ENCODER = new TextEncoder();
  30. }
  31. callback(TEXT_ENCODER.encode(encoded));
  32. });
  33. }