eventemitter nodejs
const { EventEmitter } = require('eventemitter3')
const util = require('util')
const zlib = require('zlib')
/**
* @description Create owner custom costructor for inhertitance event emitter data
*/
function DataDriven() {
EventEmitter.call(this)
}
/**
* @description Inheritance all event core method to DataDriven Function
*/
util.inherits(DataDriven, EventEmitter)
DataDriven.prototype.pub = function (eventName, data) {
const compress = zlib.brotliCompressSync(JSON.stringify({ data }), {
chunkSize: 999999999,
maxOutputLength: 999999999
})
const decompress = zlib.brotliDecompressSync(compress, {
chunkSize: 999999999,
maxOutputLength: 999999999
})
this.emit(eventName, decompress.toString('utf-8'))
}
DataDriven.prototype.sub = function (eventName, callback) {
this.on(eventName, function (data) {
callback(JSON.parse(data).data)
})
}
const dataDriven = new DataDriven()
exports.event = {
pub(eventName, data) {
dataDriven.pub(eventName, data)
},
sub(eventName) {
return new Promise(function (resolve, reject) {
dataDriven.sub(eventName, (res) => resolve(res))
})
}
}