5

I'm kinda new to Web Dev, especially in node and I'm struggling with socket.io. The problem is that I need to export my "io" in an other file to emit messages but it's not working, cause I probably do it the wrong way.

I've tried many of the stackOverflow solutions, but didnt manage to succeed.

The two files are server.js, where is the config of the socket:

let server = http.createServer(app);
let io_fin=io_test.listen(server);
module.exports= io_test;

and in the same file, my "emit request" is working:

io_fin.on('connection', function(socket){
    console.log('an user connected');

    socket.emit('chat message', 'TESTING');
  });

In the other file, I've got this import :

let yoyo = require('socket.io');

and I'm try to emit like this:

yoyo.emit('chat message', 'TEST2');

And the api is crashing saying "yoyo.emit is not a function".

I've tried a lot of different ways to export it like:

  • module.exports= io_test(server);

  • module.exports= io_fin;

  • module.exports= io_test.listen(server);

  • etc..

And I feel like I'm doing I've missed a key concept of the sockets, because I'm totally stuck ! Sorry for this "newbye" issue, but I feel like I would really use some help. Thanks in advance.

Cosack
  • 63
  • 4

1 Answers1

2

let yoyo = require('socket.io') This line is requiring, a new, socket.io function.

You're exporting in your server.js, so you should import from that file like:

// assuming the file you're importing from is in the same folder as server.js
let yoyo = require('./server');
1565986223
  • 6,420
  • 2
  • 20
  • 33