encodePacket.js 822 B

123456789101112131415161718192021222324252627
  1. const { PACKET_TYPES } = require("./commons");
  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. } else if (data instanceof ArrayBuffer) {
  14. return Buffer.from(data);
  15. } else {
  16. return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
  17. }
  18. };
  19. // only 'message' packets can contain binary, so the type prefix is not needed
  20. const encodeBuffer = (data, supportsBinary) => {
  21. return supportsBinary ? data : "b" + data.toString("base64");
  22. };
  23. module.exports = encodePacket;