1

I want to make my socket.io connection modular, to make it run once even if I need it anytime and everywhere. How to I export it?

var server = require("http").Server(express);  
var io = require("socket.io")(server);
server.listen(5000);
io.on('connection', function(client) {
  client.on('order_'+userId, function(data) {
      io.emit('order_'+userId,data); // emit to cilent of dashboard
  });
});

How does required work? I'm seeing different pattern like

var moment = require('moment');

or sometime

var LocalStorage = require('node-localstorage').LocalStorage;

In my case I need not to assign it to any variable, and want it to execute on the fly. Possible?

Alicia Brandon
  • 545
  • 2
  • 6
  • 13
  • Possible duplicate of [What is the purpose of Node.js module.exports and how do you use it?](http://stackoverflow.com/questions/5311334/what-is-the-purpose-of-node-js-module-exports-and-how-do-you-use-it) – docksteaderluke Jun 28 '16 at 15:59

1 Answers1

0

require() returns what the module exports. It can be either an Object, a function, or even a String or a Number. It's usually either Object or function though. For example, var server = require('http') returns an Object, which has a Server() method (which you call in the first line of your code sample). It's up to the author of the package, really.

Your code seems OK to me. socket.io is assigned to a variable because that's how you reference it later. io.on('connection', ...) is effectively only called once. This will wait for a connection, and every time a connection event happens, function(client) {...} will be called. There is no major performance problem with this implementation.

Samuel Bolduc
  • 18,163
  • 7
  • 34
  • 55