ddgg
ddgg

Reputation: 307

how to export modules that requires other modules

I'm working on a node js project that is getting bigger and bigger, and I'm trying to tidy up my code. This is just a case example.

this is my index.js:

const express = require('express')
const app = express()
const http = require('http').Server(app);
const io = require('socket.io')(http)

io.on('connection', socket => {
  socket.on('message', () => doSomething())
})

http.listen(4000, () => console.log('server started'))

and I'd like to import doSomething from another file (say functions.js) like this:

function doSomething(){
  console.log(io.sockets.adapter.rooms);
}

module.exports =  { doSomething }

modifying index.js as follows:

[...]
const library = require('./functions.js')
[...]
socket.on('message', () => library.doSomething())

but of course: io is not defined in functions.js.

QUESTION: How could I import the required modules so that they are shared in both files?

Upvotes: 0

Views: 218

Answers (2)

Saeed
Saeed

Reputation: 5488

Write your function.js file as below:

function doSomething(){
  let self = this;
  console.log(self.io.sockets.adapter.rooms);
}

module.exports = function (io) {
  let self = this;
  self.io = io;
  return {
    doSomething: doSomething.bind(self)
  };
};

And its usage in index.js file will be:

const Library = require('./functions.js');
const library = Library(io);

socket.on('message', () => library.doSomething())

Upvotes: 1

LearningEveryday
LearningEveryday

Reputation: 584

You will have to include the required packages in your functions.js.

Your functions.js should be something like

const io = require('socket.io')(http)
//Include other packages here
function doSomething(){
  console.log(io.sockets.adapter.rooms);
}

//Other functions here

//Export all that you need to be exported
module.exports =  { doSomething }

Upvotes: 0

Related Questions