I'm currently using socket.io
to emit and listen to events between a client-side JavaScript file and a Node.js server file, but I'd like to be able to emit and listen to events between the Node server and its modules. My thought is that it would look something like this:
Node server:
var module1 = require('./module1');
//Some code to launch and run the server
module1.emit('eventToModule');
module1.emit('moduleResponse', function(moduleVariable) {
//server action based on module response
}
Module file:
var server = require('./server.js');
server.on('eventToModule', function() {
//module response to server request
}
server.emit('moduleResponse', moduleVariable);
This is obviously a simplified version but I would think that this functionality should be available. Do I need to set up the module file as a second server? If so, what would that look like?
I also tried using var socket = io.connect('http://localhost:3000');
(this is the code I use to allow the client to connect to the Node server) instead of server
and had module1
listen on and emit to socket
but that didn't work either.
SECOND ATTEMPT (still not working):
server.js
//other requirements
var module1 = require('./module');
const EventEmitter = require('events');
var emitter = new EventEmitter();
io.on('connection', function(client) {
client.on('emitterTester', function() {
emitter.emit('toModule');
emitter.on('toServer', function() {
console.log(Emitter successful.);
});
});
});
module.exports = emitter;
module.js
var server1 = require('./server');
const EventEmitter = require('events');
var emitter = new EventEmitter();
emitter.on('toModule', function() {
console.log(Emitter heard by module.);
emitter.emit('toServer');
});
module.exports = emitter;
Also, when I try to use server1.on
, I get the message server1.on is not a function
.