【发布时间】:2018-04-07 17:16:20
【问题描述】:
我对 node.js 还是很陌生,希望你能帮助我。
我使用 Node (v7.9.0) 与模块 express (4.15.2) 和 socket.io (1.7.3) 来创建一个简单的网络服务器并将事件从网络服务器发送到连接的客户端。
我正在尝试模块化我的应用程序,并希望在不同的 js 文件上向客户端发出不同的事件。
现在这是我当前的代码:
--- start.js:
// Configure the build-in webserver
var
express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
conf = require('./serverConfig.json');
module.exports = server; // Export to use with uart_functions.js
module.exports.io = io; // Export to use with uart_functions.js
server.listen(conf.port); // Configure the server to port 8080
app.use(express.static(__dirname + '/pages')); // All the website data is in this folder
app.get('/', function(req, res) {
res.sendfile(__dirname + '/pages/index.html'); // Webserver should return the page index.html
});
console.log("Server is opened: http://127.0.0.1:" + conf.port +"/\n");
io.sockets.on('connection', function(socket) {
console.log("Verbunden!!!\n");
io.sockets.emit('chat', {zeit: new Date(), name: "Server", text: "Du bist nun mit dem Server verbunden!"}); // Send Data to Client. This works
});
--- uart_functions.js:
var ioSocket = require('./start.js').io;
function TelegrammID1() {
console.log("RUN ID 1\n");
ioSocket.sockets.emit('chat', {zeit: new Date(), name:'Tester', text: "Das ist ein Test"}); // Send data to client - This doesn't work
}
现在在 uart_functions.js 文件中出现错误:“TypeError: Cannot read property 'sockets' of undefined.”
我了解错误发生的原因。但我不知道我仍然需要通过 module.export 将文件 start.js 传递给文件 uart_functions.js 的内容和方式
关于搜索我发现如下:Cannot read property 'socket's of undefined when exporting socket.io
很遗憾,没有有用的答案。 感谢您的帮助
【问题讨论】:
标签: node.js