gpt4 book ai didi

javascript - NodeJS 发出事件未触发

转载 作者:行者123 更新时间:2023-12-01 03:36:18 25 4
gpt4 key购买 nike

我有这个 NodeJS 代码,我不知道为什么 emit 函数没有触发,只有当我将它放入像 这样的回调函数中时它才会触发>设置超时

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

最佳答案

您似乎没有立即使用 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');
});

关于javascript - NodeJS 发出事件未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44260086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com