here is the challenge question that required to write a case against eventemitter sends JSON causing the error. follow by the close event. the eventemitter will emit a close event before going offline. the client will listen for the close event, then process the buffer data after error had been encountered.
here is the line to handle the close event that processed the data left in the buffer after throwing an error in the client.
stream.on('close', ()=>{
this.emit('message',JSON.parse( buffer));
})
the following line will set up the test case. stream emit the Json Data without newline, following by emitting a close event.
it('test case on close event',done=>{
client.on('message', message=> {
console.log(message);
assert.deepEqual(message, {foo: 'bar'});
done();
});
stream.emit('data','{"foo": "bar"}');
stream.emit('close');
});
LDJClient.js
'use strict';
const EventEmitter=require('events').EventEmitter;
class LDJClient extends EventEmitter {
constructor(stream){
super();
let buffer='';
stream.on('data',data=>{
console.log(data);
buffer +=data;
let boundary=buffer.indexOf('\n');
while(boundary !=-1){
const input=buffer.substring(0, boundary);
buffer=buffer.substring(boundary+1);
this.emit('message', JSON.parse(input));
boundary=buffer.indexOf('\n');
}
});
stream.on('close', ()=>{
this.emit('message',JSON.parse( buffer));
})
}
static connect(stream){
return new LDJClient(stream);
}
}
module.exports=LDJClient;
test-ldj-client.js
'use strict';
const assert=require('assert');
const EventEmitter=require('events').EventEmitter;
const LDJClient=require('../lib/ldj-client.js');
describe('LDJClient', ()=>{
let stream=null;
let client=null;
beforeEach(()=>{
stream=new EventEmitter();
client=new LDJClient(stream);
});
it('should emit a message event for a single data event', done=> {
client.on('message', message=> {
assert.deepEqual(message, {foo: 'bar'});
done();
});
stream.emit('data','{"foo": "bar"}\n');
//stream.emit('data','{"foo":');
//process.nextTick(()=> stream.emit('data', '"bar"}\n'));
});
it('test case on close event',done=>{
client.on('message', message=> {
console.log(message);
assert.deepEqual(message, {foo: 'bar'});
done();
});
stream.emit('data','{"foo": "bar"}');
stream.emit('close');
});
});
the output of test case is succeed. cheers
No comments:
Post a Comment