I found an example of creating an event Emitter class that takes a stream (tcp net connection) and emits it's own custom events from the data events it pulls off of that stream.
No matter what I do I can't remake it will es6 class syntax. I saw in the node docs that this should be possible. But I have a weak OOP background and I just can't get the thing to work.
I'm sure someone could easily figure it out tho. Here is the original class (es5 style constructor / util module for extending...)
const MsgClient = function(stream) {
events.EventEmitter.call(this);
let self = this, buffer = "";
stream.on("data", (data) => {
buffer += data;
let boundary = buffer.indexOf("\n");
while (boundary !== -1) {
let input = buffer.substr(0, boundary);
self.emit("message", JSON.parse(input));
buffer = buffer.substr(boundary + 1);
boundary = buffer.indexOf("\n");
}
})
}
util.inherits(MsgClient, EventEmitter); // from require("events").EventEmitter
In my naivety I've tried the following, but I just don't have the background to not get lost when it doesn't work. "This" gets really convoluted if you're not used to it...
class MsgClient extends EventEmitter {
constructor(stream) {
super();
this.stream = stream;
this.buffer = "";
self = this;
}
stream.on("data", (data) => {
buffer += data;
let boundary = buffer.indexOf("\n");
while (boundary !== -1) {
let input = buffer.substr(0, boundary);
self.emit("message", JSON.parse(input));
buffer = buffer.substr(boundary + 1);
boundary = buffer.indexOf("\n");
}
})
};
If anyone could help or even point me in the write direction it would be much appreciated.