Take this code, where f
is a stream that has an event 'body', which calls the listeners with a m
-- which is itself a stream emitting events:
f.on('message', function(m) {
m.on('body', function(stream, info) {
var b = '';
stream.on('data', function(d) {
b += d;
});
stream.on('end', function() {
if (/^header/i.test(info.which))
msg.header = Imap.parseHeader(b);
else
msg.body = b;
});
});
m.on('attributes', function(attrs) {
msg.attrs = attrs;
msg.contentType = partID[1];
});
});
f.on('end', function() {
if (hadErr)
return;
cb(undefined, msg);
});
The backend is emitting a 'message' event, passing it a m
object. The code then listens to the events body
and attributes
. It's all straightforward except that my little brain is in a bit of a crisis (I am not used to dealing with streams). Especially: how is the backend emitting from the f
and m
objects, to guarantee that events are indeed called at the right time?
Specifically:
- How would
f
have to be coded, in general terms, in order to make sure thatm
m doesn't emit tillm.on('body', function(stream, info) {
is called? - Does a listener need to be added with on() before the event is emitted in order for it to be caught?
- If so, does that mean that
f
andm
will emit events after the code here has registered? - If the backend is supposed to guarantee that
b.emit('end')
is called after m.emit('end'), how is that even supposed to happen really, still guaranteeing thaton()
is calledbefore
any one of the events are emitted?
OK I am 100% confused about this matter. I am obviously missing something basic and crucial, and I am not even able to ask the right questions because of this...! (Apologies)