0

In first file I have:

const io = require('socket.io')(process.env.IO_PORT);

io.on('connection', socket => {
        socket.on('user.go', data => {
            console.log('go');
     }
}

In second file I need to access socket object from callback. How can I export it and use it in another file. Code:

socket.emit(`add.message`, {
      sender
});

Please advise!

2 Answers 2

0

I think you could use socket-io-client to start a new connection

https://socket.io/docs/client-api/

like here

import io from 'socket.io-client';

const socket = io('http://localhost');
1
  • I do not need new connection. I need socket from existing connection.
    – Nastro
    Aug 20, 2019 at 19:40
0

You can't export a specific socket, but you can make a function that will receive the socket as argument in other file/s

fileA

const io = require('socket.io')(process.env.IO_PORT);
const sendMessage = require('./fileB');

io.on('connection', socket => {
  socket.on('user.go', data => {
    console.log('go');
    sendMessage(socket);
  });
});

fileB

module.exports = socket => socket.emit(`add.message`, 'hello');
1
  • I have a function match() which runs on user action and have a socket.emit in the end of this function. match() function is in File A. I have a socket in File B. How to access socket from file B in function in file A? I tried your solution, but socket is undefined.
    – Nastro
    Aug 21, 2019 at 8:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.