has no method of emit in node.js - node.js

I made a simple example like below, and I got a error saying 'has no method of 'emit' ', what is the issue ?
var events = require('events');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var Door = function (options) {
events.EventEmitter.call(this);
}
util.inherits(Door, EventEmitter);
Door.prototype = {
open:function(){
this.emit('open');
}
}
var frontDoor = new Door('brown');
frontDoor.on('open', function() {
console.log('ring ring ring');
});
frontDoor.open();

You are replacing the prototype of Door with a new object, which overwrites (/removes) the EventEmitter prototype methods as well:
Door.prototype = {
open:function(){
this.emit('open');
}
}
Instead, just add a single entry to the existing prototype:
Door.prototype.open = function() {
this.emit('open');
};

Related

How to wait in a request and response in another request with koa

I wanna await the reponse in a request until I set value in another request. How to code this in koa?
request 1: /always-get?key=abc
request 2: /set?key=abc&val=1234
var querystring = require("querystring");
module.exports = resTest = {
awaitRes: function *(next) {
var qs = querystring.parse(this.request.querystring);
var key = qs.key;
resTest.qrResponses[key] = this.response;
// I wanna wait here, response in the next method
},
setRes: function *(next) {
var qs = querystring.parse(this.request.querystring);
var key = qs.key;
var val = qs.val;
//reponse here....
resTest.qrResponses[key].body = val;
this.body = "OK";
},
qrResponses: {}
};
router.get("/always-get", resTest.awaitRes);
router.get("/set", resTest.setRes);
This is easy in callback hell framework...
You can create an event bus to share events between them. Also, co will yield to a thunk and provide a callback. So you can yield a thunk and call the callback when you've "heard" the event with the same name emitted. Once that callback is called, the middleware chain will continue.
var Emitter = require('events');
var bus = new Emitter();
router.get('/info/:key', function* (next) {
var ctx = this;
// yield a thunk
yield function(cb) {
// this has the potential to leak event listeners!
bus.once(ctx.params.key, function(value) {
ctx.body = value;
cb();
});
};
});
router.get('/set/:key/:value', function* (next) {
bus.emit(this.params.key, this.params.value);
this.body = 'OK';
});

Custom event type not working in nodejs EventEmitter

my custom event type not working in nodejs EventEmitter. I have create a custom event type named "someMethod" but it's not working. It's not showing anything in console. Please view my code described below:
util = require('util');
var EventEmitter = require('events').EventEmitter;
//Here is the MyClass constructor:
var MyClass = function() {
}
util.inherits(MyClass, EventEmitter);
MyClass.prototype.someMethod = function() {
this.emit("customEvent", "arg1", "arg2");
};
var myInstance = new MyClass();
myInstance.on('customEvent', function(str1, str2) {
console.log('got a custom event with the str1 %s and str2 %s!', str1, str2);
});
You're not calling myInstance.someMethod() so that the event can be emitted.

Module exports and method call

I'm trying to developp a module with nodejs. My code is something like this :
var fs = require('fs');
module.exports.method1 = function () {
// Some stuff
}
module.exports.method2 = function ()
{
// Some stuff
}
I would like to do something like :
module.exports.method2 = function (url, dir, name)
{
this.method1();
}
How to do this ?
var fs = require('fs');
exports.method1 = function () {
// Some stuff
}
exports.method2 = function ()
{
exports.method1();
}
To make it a little bit swankier you could do something like:
module.exports = {
function1: function(){
//some stuff
},
function2: function(){
this.function1();
}
};
If you want private scope:
module.exports = function(){
var myPrivateVar = 'foo';
var publicObject = {
function1: function(){
//some stuff
console.log(myPrivateVar);
},
function2: function(){
this.function1();
}
};
return publicObject;
}
The difference is though that you need to invoke it where the former is just an object reference. The second example is more like a constructor function... require + invoke... var myMod = myModule(); myMod.function2() will output 'foo'
IMHO this is a more object-oriented way of doing it rather than exporting each individual function. This allows for better separation and cleaner code.

Wrapping NodeJS's net.createServer into a producer of customised sockets

I'm trying to make a function which behaves like net.createServer, except that it returns objects which are wrappers around sockets, instead of sockets.
(The point of these will be to do automatic data conversion.)
My latest attempt looks like:
var net = require('net');
var util = require('util');
var stream = require('stream');
var EventEmitter = process.EventEmitter;
exports.createServer = createServer;
function createServer(arg0, arg1) {
var server;
var netServer;
var ocb;
if (typeof arg1 === 'function') {
// options, callback
netServer = net.createServer(arg0, callback);
ocb = arg1;
} else if (typeof arg0 === 'function') {
// callback
netServer = net.createServer(callback);
ocb = arg0;
} else {
// options?
netServer = net.createServer(arg0);
ocb = null;
}
server = new Server(netServer);
function callback(socket) {
ocb(new LiftedSocket(socket));
};
return server;
;
}
function Server(netServer) {
this.netServer = netServer;
}
util.inherits(Server, EventEmitter);
Server.prototype.listen = function() {
this.netServer.listen.apply(this.netServer, arguments);
}
function LiftedSocket(socket) {
stream.Duplex(this);
this.socket = socket;
}
util.inherits(LiftedSocket, stream.Duplex);
LiftedSocket.prototype._read = function(size) {
console.log('_read', size);
// transforming code goes here
this.socket.read(size);
}
LiftedSocket.prototype._write = function(chunk, encoding, callback) {
console.log('_write', chunk, encoding, callback);
// transforming code goes here
this.socket.write(chunk, callback);
}
But when tested (by trying to pipe from a returned LiftedSocket) it fails with errors including:
Uncaught TypeError: Cannot read property 'pipesCount' of undefined
at LiftedSocket.Readable.pipe (_stream_readable.js:453:16)
Uncaught TypeError: Cannot read property 'flowing' of undefined
at LiftedSocket.Readable.on (_stream_readable.js:691:44)
I expect I'm doing something wrong when constructing the LiftedSocket, but I can't think what.
I had called the superclass constructor incorrectly. It should have been:
stream.Duplex.call(this, {})

node.js - Emit events from an object

I have the following module in node.js:
var obj = {};
obj.prop1 = "value1";
obj.prop2 = "value2";
asyncFunction(function(data) {
obj.prop3 = data;
// I would like to do: obj.emit("completed");
});
module.exports = obj;
So I can import it like:
var imp = require('./obj');
imp.on("completed", function() {
console.log("Hello!");
});
How can I do it?
You will need to make obj an EventEmitter. This can be done pretty simply - just change this:
var obj = {};
To this:
var EventEmitter = require('events').EventEmitter;
var obj = new EventEmitter();

Resources