Search code examples
javascriptnode.jssocket.ioexportrequire

Using modules.exports in main Node file


I initialized my socket.io server in my server.js file (main entry point).

EDIT 2: Importing otherfile.js in this file also

// server.js
const io = require('socket.io')(server);
const otherfile = require('otherfile.js');
io.use(//...configuration);
io.on("connection",otherfile);

module.exports = {io: io}

Now I want to use this same io object in another file

EDIT 1: To clarify, I am calling the exported variable in an export block like so:

// otherfile.js

const io = require('./server.js')['io'];

module.exports = {
    function(socket){
        // do stuff...
        io.emit("event", payload);
          }
}

When I run it, I get an error

Type Error: Cannot read '.on' property of undefined

Something like that.

Why can't I access code from the main js file?


Solution

  • I figured it out after reading this great article (well, parts of it :p) about requiring modules in Node. Under "Circular Module Dependency".

    The problem was, I was exporting the io object after I had required the 'otherfile.js' so the io object had not yet been exported and therefore undefined in 'otherfile.js' when the code is called.

    So just export io object before requiring 'otherfile.js'.

    // server.js
    module.exports = {
         io: io
         }
     const otherfile = require("otherfile.js");
     // listen for events...