var gzip = require("util").promisify(require("zlib").gzip); module.exports = class WebSocketMessageCollector { constructor(dispatchFunction) { this.maxSize = 8000000; this.data = ""; this.startDate = new Date(); this.dispatchFunction = dispatchFunction; exitHook(cb => { this.package().then(cb); }); } collect(message) { message = message.data || message; if (message instanceof ArrayBuffer) message = Buffer.from(message).toString('base64'); var line = `${Date.now()} ${message}\n`; this.data += line; if (this.data.length > this.maxSize) this.package(); } async package() { var data = this.data, startDate = this.startDate, endDate = new Date(); this.data = "", this.startDate = new Date(); data = await gzip(data); await this.dispatchFunction(data, startDate, endDate); } }