【发布时间】:2020-07-17 07:12:31
【问题描述】:
我正在尝试创建一个从 WebSocket 服务器返回传入信息的函数。
我希望它在完成后在主文件中看起来像这样:
const getMessage = require('./getMessage.js');
let message = getMessage();
console.log(message);
现在我的问题是我不知道如何从事件监听器返回传入的消息
websocket.on('message', function incoming(reply) {
});
我的 getMessage.js 文件如下所示:
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost');
module.exports = function getMessage() {
let msg;
ws.on('message', function incoming(reply) {
msg = reply;
});
return msg;
}
但不是返回传入的消息,而是返回未定义的。如何在一个函数中获取 Websocket 服务器的传入消息?
index.js 的当前代码:
const api = require('./api.js');
let message = api();
console.log(messag);
api.js 的当前代码:
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost');
let api = (function(msg) {
console.log(msg);
return msg;
});
ws.on('message', function msg(reply) {
api(reply);
});
如果我运行它记录的程序:
未定义
未定义
你好
【问题讨论】:
标签: node.js websocket node-modules