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 860B

12345678910111213141516171819202122232425
  1. import { PACKET_TYPES } from "./commons.js";
  2. const encodePacket = ({ type, data }, supportsBinary, callback) => {
  3. if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
  4. const buffer = toBuffer(data);
  5. return callback(encodeBuffer(buffer, supportsBinary));
  6. }
  7. // plain string
  8. return callback(PACKET_TYPES[type] + (data || ""));
  9. };
  10. const toBuffer = data => {
  11. if (Buffer.isBuffer(data)) {
  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. // only 'message' packets can contain binary, so the type prefix is not needed
  22. const encodeBuffer = (data, supportsBinary) => {
  23. return supportsBinary ? data : "b" + data.toString("base64");
  24. };
  25. export default encodePacket;