I'm still quite new to node.js and hope you can help me.
I use Node (v7.9.0) with the modules express (4.15.2) and socket.io (1.7.3) to create a simple webserver and send events from the webserver to the connected client.
I'm trying to modularize my application and would like to emit different event to client on different js files.
Now this is my current code:
--- 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
}
Now in the file uart_functions.js i get the error: "TypeError: Cannot read property 'sockets' of undefined."
I understand why the error occurs. But I do not know what and how I still have to pass over the file start.js by module.export to the file uart_functions.js
About the search I have found the following:Cannot read property 'socket's of undefined when exporting socket.io
Unfortunately there was no useful answer. Thanks for your help
via Markus Wilde
No comments:
Post a Comment