简体   繁体   中英

require and export confusion in express.js (node.js)

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM