Reputation: 1855
I have this NodeJS
code, and I have no idea why the emit
function is not firing, It only fires when I put it inside a callback function like setTimeout
const url = require('url');
const WebSocket = require('ws');
const events = require('events');
WebSocketServer = new events.EventEmitter();
WebSocketServer.start = (server) => {
const wss = new WebSocket.Server({server});
console.log('websocket started');
WebSocketServer.emit('started');
};
module.exports = WebSocketServer;
Here I test if emitted:
const ExpressServer = require('./server/api/expressServer');
const WebsocketServer = require('./server/websocket/websocketServer');
WebsocketServer.start(ExpressServer.server);
WebsocketServer.on('started', () => {
console.log('web socket emitted');
ExpressServer.start();
});
Upvotes: 0
Views: 2058
Reputation: 1855
Ok, the problem was the order, first listen to events and then fire fuctions:
const ExpressServer = require('./server/api/expressServer');
const WebsocketServer = require('./server/websocket/websocketServer');
WebsocketServer.on('started', () => {
console.log('web socket emitted');
ExpressServer.start();
});
WebsocketServer.start(ExpressServer.server);
Upvotes: 1
Reputation: 348
It seems like you are not using EventEmitter and Websocket the right away. Below is a working example of both combined:
const EventEmitter = require('events').EventEmitter(); //You didnt call EventEmitter() in your code
const WebSocket = require('ws');
const ws = new WebSocket(//Your path here);
ws.on('open', function open() {
console.log('websocket started');
EventEmitter.emit('started');
});
Upvotes: 1