0

I am working on a node project where I need to use websockets. I got the basic implementation working for socket.io in my project. Here is the code for server.js so far

import app from '../app';    
import http from 'http';
import socket from 'socket.io';

    var server = http.createServer(app);
    server.listen(app.get("port"));
    server.on('error', onError);
    server.on('listening', onListening);

    const io = socket(server);
    io.on('connection', (socket) => {
      console.log(`connected ${socket.id}`);
      socket.on('disconnect', () => {
        console.log('disconnected');

      });
    });

Now if I need to call socket from another javascript file, how do I do that? Something like this: From a.js I would like to call emit message from download function. The problem is that I don't have reference to socket object in a.js. It was defined in my server.js file. Any suggestions?

export const download = () => {
  //after file is downloaded, emit message using socket.io to user

}
RC_02
  • 3,146
  • 1
  • 18
  • 20

1 Answers1

0

you need to inject the object into a function that you're calling. is a Dependency Injection principle in programming. you can a.js

export const download = (io) => { // io is the reference
    //do something with io like io.emit
}

then in your server you need to import the download function then pass the io in your code.

import {download} from "<src/file/of/a.ts>"
// somewhere in the code in server.js
download(io);

for Dependency Injection Principle reference https://en.wikipedia.org/wiki/Dependency_injection and What is dependency injection?