Last change
on this file since 6a80231 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago |
initial commit
|
-
Property mode
set to
100644
|
File size:
822 bytes
|
Rev | Line | |
---|
[6a3a178] | 1 | const { PACKET_TYPES } = require("./commons");
|
---|
| 2 |
|
---|
| 3 | const encodePacket = ({ type, data }, supportsBinary, callback) => {
|
---|
| 4 | if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
|
---|
| 5 | const buffer = toBuffer(data);
|
---|
| 6 | return callback(encodeBuffer(buffer, supportsBinary));
|
---|
| 7 | }
|
---|
| 8 | // plain string
|
---|
| 9 | return callback(PACKET_TYPES[type] + (data || ""));
|
---|
| 10 | };
|
---|
| 11 |
|
---|
| 12 | const toBuffer = data => {
|
---|
| 13 | if (Buffer.isBuffer(data)) {
|
---|
| 14 | return data;
|
---|
| 15 | } else if (data instanceof ArrayBuffer) {
|
---|
| 16 | return Buffer.from(data);
|
---|
| 17 | } else {
|
---|
| 18 | return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
---|
| 19 | }
|
---|
| 20 | };
|
---|
| 21 |
|
---|
| 22 | // only 'message' packets can contain binary, so the type prefix is not needed
|
---|
| 23 | const encodeBuffer = (data, supportsBinary) => {
|
---|
| 24 | return supportsBinary ? data : "b" + data.toString("base64");
|
---|
| 25 | };
|
---|
| 26 |
|
---|
| 27 | module.exports = encodePacket;
|
---|
Note:
See
TracBrowser
for help on using the repository browser.