NodeJS发出的事件没有触发

时间:2017-05-30 10:46:21

标签: javascript node.js

我有这个NodeJS代码,我不知道为什么emit函数没有触发,它只会在我把它放在像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;

这里我测试是否发出:

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();
});

2 个答案:

答案 0 :(得分:1)

好像你没有马上使用EventEmitter和Websocket。下面是两个组合的工作示例:

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');
});

答案 1 :(得分:1)

好的,问题是订单,首先听事件,然后点火:

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);