Search code examples
javascriptnode.jsservereventemitter

How to require one module in the other for using event emitters?


I have an express server file like this

const express = require('express')
const app = express()

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(3000, () => console.log('Example app listening on port 3000!')

And I have a file for running a different port for a tcpServer

const net = require('net');
const lora_packet = require('lora-packet');
const dataParser = require('./dataParser');

const clients = [];


net.createServer(function(socket) {
    socket.name = socket.remoteAddress + ":" + socket.remotePort;
    clients.push(socket);


    socket.on('data', function(data) {
        try {
            console.log("Buffer sent by terminal : ");

        }catch(err){
            console.log("DATA RECEIVING PRODUCED AN ERROR" + err);
        }

    });
    socket.on('end', function() {
        clients.splice(clients.indexOf(socket), 1);
        //broadcast(socket.name + "has left the cartel.\n");
    });

    socket.on('error', function (exc) {
        console.log("ignoring exception: " + exc);
    });



}).listen(8080);

I want to use event emitters in both the modules to notify the changes in one of the servers to the other one. But the problem I'm facing is that to emit an event I must require the other module and wouldn't it create circular dependency? How should I approach this problem? Is circular dependency problematic or it can be used in your node.js servers?

Can there be a work around the circular dependency to attain the objective or not?


Solution

  • While Node.JS has several ways for handling circular dependencies, dynamical requires are usually a bad idea - it can create many unpredictable situations. It's best to require all the modules you need and then just use them in emitters.