How can i export socket.io into other modules in nodejs?
Since app.js is usually kind of the main initialization module in your app, it will typically both initialize the web server and socket.io and will load other things that are needed by the app.
As such a typical way to share io
with other modules is by passing them to the other modules in that module's constructor function. That would work like this:
var server = require('http').createServer(app);
var io = require('socket.io')(server);
// load consumer.js and pass it the socket.io object
require('./consumer.js')(io);
// other app.js code follows
Then, in consumer.js:// define constructor function that gets `io` send to it
module.exports = function(io) {
io.on('connection', function(socket) {
socket.on('message', function(message) {
logger.log('info',message.value);
socket.emit('ditConsumer',message.value);
console.log('from console',message.value);
});
});
};
Or, if you want to use a
.start()
method to initialize things, you can do the same thing with that (minor differences):// app.js
var server = require('http').createServer(app);
var io = require('socket.io')(server);
// load consumer.js and pass it the socket.io object
var consumer = require('./consumer.js');
consumer.start(io);
// other app.js code follows
And the start method in consumer.js// consumer.js
// define start method that gets `io` send to it
module.exports = {
start: function(io) {
io.on('connection', function(socket) {
socket.on('message', function(message) {
logger.log('info',message.value);
socket.emit('ditConsumer',message.value);
console.log('from console',message.value);
});
});
};
}
This is what is known as the "push" module of resource sharing. The module that is loading you pushes some shared info to you by passing it in the constructor.
There are also "pull" models where the module itself calls a method in some other module to retrieve the shared info (in this case the io
object).
Often, either model can be made to work, but usually one or the other will feel more natural given how modules are being loaded and who has the desired information and how you intend for modules to be reused in other circumstances.
How to export Socket.io instance on other files of the project
let yoyo = require('socket.io')
This line is requiring, a new, socket.io
function.
You're exporting in your server.js
, so you should import from that file like:
// assuming the file you're importing from is in the same folder as server.js
let yoyo = require('./server');
How can i share socket.io into other modules in nodejs?
You can export not only the function that initiates the server, but a class that handles all the socket.io connection and functionality. This class will be a singleton and will have functions that uses the connection, and can be usable in the different modules.
example:
app.js:
'use strict'
const express = require('express');
const realtime = require('./controllers/realtime');
const app = express();
const server = require('http').Server(app);
var sessionMiddleware = session(sessionConfig);
realtime.connect(server,sessionMiddleware);
realtime.js:let connection = null;
class Realtime {
constructor() {
this._socket = null;
}
connect(server,sessionMiddleware) {
const io = require('socket.io')(server);
io.use(function(socket, next) {
sessionMiddleware(socket.request, socket.request.res, next);
});
io.on('connection', (socket) => {
this._socket = socket;
this._socket.on('statusConnetion',(data)=>{
console.log(data)
});
this._socket.on('disconnect', function () {
console.log(socket.id,"Un socket se desconecto");
});
console.log(`New socket connection: ${socket.id}`);
});
}
sendEvent(event, data) {
this._socket.emit(event, data);
}
registerEvent(event, handler) {
this._socket.on(event, handler);
}
static init(server,sessionMiddleware) {
if(!connection) {
connection = new Realtime();
connection.connect(server,sessionMiddleware);
}
}
static getConnection() {
if(!connection) {
throw new Error("no active connection");
}
return connection;
}
}
module.exports = {
connect: Realtime.init,
connection: Realtime.getConnection
}
cargos.js:const express = require('express');
const router = express.Router();
let cargos = {};
cargos.update = (req, res, next) =>{
const connection = require('./controllers/realtime').connection();
connection.sendEvent("update", {params: req.params});
}
module.exports = cargos;
Reference socket.io instance in another file with multiple exports (node.js)
In below code I have exported io object from app.js and you can easily use it where you want
const server = require('http').createServer(app);
const io = require('socket.io')(server, {
cors: {
origin: 'http://localhost:8081',
methods: ['GET', 'POST'],
allowedHeaders: ['my-custom-header'],
credentials: true,
},
});
io.on('connection', async (socket) => {
console.log('socket connected', userId)
if (io.nsps['/'].adapter.rooms["room-" + userId] && io.nsps['/'].adapter.rooms["room-" + userId].length > 0) userId++;
socket.join("room-" + userId);
io.sockets.in("room-" + userId).emit('connectToRoom', "You are in room no. " + userId);
});
const socketIoObject = io;
module.exports.ioObject = socketIoObject;
where you want to get that function use below codeconst socket = require('../app');//import object
socket.ioObject.sockets.in("_room" + room_id).emit("hello", "how are you");
Related Topics
Getusermedia() in Chrome 47 Without Using Https
Get Selected HTML in Browser via JavaScript
Finding "Line-Breaks" in Textarea That Is Word-Wrapping Arabic Text
Typeerror: Cannot Read Property 'Setstate' of Undefined
Passing Data to a Jquery UI Dialog
How to Randomly Generate HTML Hex Color Codes Using JavaScript
How to Check If an Array Is a Subset of Another Array in JavaScript
Read/Write Bytes of Float in Js
React 18, Useeffect Is Getting Called Two Times on Mount
How to Sort an Associative Array by Its Values in JavaScript
How to Invoke "Click" Event Programmatically in D3
How to Get Size of an Element/List in Firebase Without Get It All
Render Object Properties in React
What Is the 'Execution Context' in JavaScript Exactly