'Sharing' object between NodeJS modules - node.js

I'm new to NodeJS development and I'm doing some tests with the socket.io library. Basically, what I want to do is to stablish a socket.io connection between the clients (Angular 6 web app) and the server and broadcast a message when a new user connects.
Right now, the code is quite simple, and this is what I have:
app.js
var express = require('express');
var http = require('http');
var socketIO = require('socket.io');
// Routes
var twitterRoutes = require('./routes/user');
var app = express();
var server = http.Server(app);
var io = socketIO(server); // <== THIS OBJECT IS WHAT I WANT TO USE FROM THE ROUTES
[ ... ]
io.on('connect', (socket) => {
console.log('New user connected');
socket.on('disconnect', (reason) => {
console.log('User disconnected:', reason);
});
socket.on('error', (err) => {
console.log('Error in connection: ', err);
});
});
I want to use the io object inside the user route, but I don't know how to do it:
routes/user.js
var express = require('express');
var config = require('../config/config');
var router = express.Router();
router.post('/login', (req, res, next) => {
// DO ROUTE LOGIC
// I WANT TO BROADCAST THE NEW LOGGED USER USING io.broadcast.emit, BUT DON'T KNOW HOW
// <=====
});
How could I do it? Thanks in advance,

Not sure if it is the best way but you could share things between request handlers using middleware
// define and use a middleware
app.use(function shareIO(req, res, next) {
req.io = io;
next();
})
Then you could use req.io inside request handlers.
router.post('/login', (req, res, next) => {
// DO ROUTE LOGIC
req.io.emit('event')
});

You could do what you want by injecting your IO var in a function
// app.js
var app = express();
var server = http.Server(app);
var io = socketIO(server);
server.use(require('./router')(io))
...
// router.js
module.exports = function makeRouter(io) {
var router = express.Router();
router.post('/login', (req, res, next) => {
// do something with io
}
return router
}

I don't know if it's the best practice, but I've assigned the io object to a property of the global object, and I can access it from everywhere all across the application. So this is what I did:
app.js
var io = socketIO(server);
global.ioObj = io;
routes/user.js
router.post('/login', (req, res, next) => {
// DO ROUTE LOGIC
if (global.ioObj) {
global.ioObj.sockets.clients().emit('new-message', { type: 'message', text: 'New user has logged in' });
}
});

Related

How use socket.io in express routes with node.js

I'm using Express with Socket.io in the server side but i can't use out of app.js, i need how to use SocKet.io in Express routes.
app.js
...
let http = require('http').Server(app);
let io = require('socket.io')(http);
io.on('connection', (socket) => {
console.log('user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('message', (message) => {
console.log("Message Received: " + message);
io.emit('message', {type:'new-message', text: message});
});
});
...
this work ok, but i have other routes where configure my methods, POST, GET ... EX
routesActividad.js
...
function http(){
this.configActividad= function(app){
// get actividades by id
app.get('/actividad/:NUM_ID_EMPLEADO', function(req, res) {
//... code here...//
.then(function (actividad) {
res.json(actividad);
}).catch(error => res.status(400).send(error));
})
app.post('/actividad/', function(req, res){
// code here //
})
app.put('/actividad/', function(req, res){
// code here //
})
}
}
module.exports = new http();
how i can use socket in routesActividad.js and other routes like this, for use emit or scoket.on y this routes
app.js
...
var routesActividad = require('./routes/routesActividad');
routesActividad.configActividad(app);
// more routes
...
thanks
Hello you just need to pass the IO instance by parameter to your external module:
app.js
let http = require('http').Server(app);
let io = require('socket.io')(http);
let actividad = require('routesActividad')(io);
routesActividad.js:
function http(io){
//put the IO stuff wherever you want inside functions or outside
this.configActividad= function(app){
// get actividades by id
app.get('/actividad/:NUM_ID_EMPLEADO', function(req, res) {
//... code here...//
.then(function (actividad) {
res.json(actividad);
}).catch(error => res.status(400).send(error));
})
app.post('/actividad/', function(req, res){
// code here //
})
app.put('/actividad/', function(req, res){
// code here //
})
}
}
module.exports = http; //Removed new statement

NodeJS/Express Room Joining when a View is accessed - Sockets

I'm creating a simple NodeJS/Express webapp that has an api and sockets. Basically, what I want to do is send data to my API from an external source, and then send this data to the socket in pageView/id. Right now it works, but it is sending data to all of the views, not the specific pageView/id.
I know I have to create Rooms and I tried doing this by having my sockets join the room when the webapp is navigated to page/id: (note I do not have logged in users)
router.get('/:id', function (req, res, next) {
res.io.on('connection', function(socket) {
console.log("user connected");
//join room here
});
});
But then this creates multiple connections, every time I refresh the pageView I get a new connection + previous connections on my server side.
How can I join the room when a pageView/id is accessed? Here is my setup...
app.js
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
app.use(function(req, res, next){
res.io = io;
next();
});
module.exports = {app: app, server: server};
/bin/www
var app = require('../app').app;
var http = require('http');
var server = require('../app').server;
server.listen(port);
pageView.hbs
var socket = io.connect();
socket.on('mySocket', function (data) {
console.log(data);
});
pageView.js
router.post('/updatePage', function (req, res, next){
//send to the view
res.io.emit("mySocket", {
device: device
});
});
Ok, I understand now, your mistake is to create the listeners inside your route. You need only one set of event listeners on io. So, this would work :
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.on('connection', function(socket) {
console.log("user connected");
socket.join(room);
});
module.exports = {app: app, server: server};
remember that you can pass parameters on your connection, for example, you can do :
var myroom = window.location.pathname.split('pageView/')[1]; //example to get room name, be creative !
var socket = io.connect("http://127.0.0.1:3000/", { query: 'room='+myroom+' });
and on the server :
io.on('connection', function(socket) {
console.log("user connected");
var room = socket.handshake.query.room; // === 'myRoom'
socket.join(room);
socket.emit("mySocket", {
device: device
});
});
pageView.js
router.post('/updatePage', function (req, res, next){
});

NodeJS, socketIO, multiple files

I'm a little bit confused;
I would like to use socketIO on NodeJS app.
I've created this (pseudo)code:
//server.js
var app = express();
//some code...
var router = require('./app/router');
app.use(router);
var server = app.listen(appConfig.app.port, function () {
var port = server.address().port;
});
var io = require('socket.io')(server);
io.on('connection', function (client) {
console.log('Client connected...');
client.on('join', function (data) {
console.log(data);
});
});
//client.js
var socket = io.connect('http://localhost:5555');
socket.on('connect', function(data) {
socket.emit('join', 'Hello World from client');
});
Everything is fine. But !
At now, I would like to emit event in another file.
I have router and POST request. I want to emit event on POST request (request handler is in another file).
//router.js
router.route("/addmenu").post(function (req, res) {
menuModel.addMenu(req.body,function(data){
//I WANT EMIT HERE
res.json(data)
});
};
);
I have to initialize router before start server, but I have to pass server to IO... How pass IO to router ?
You can try this
//server.js
var app = express();
//some code...
var io;
var getIOInstance = function(){
return io;
};
var router = require('./app/router')(getIOInstance);
app.use(router);
var server = app.listen(appConfig.app.port, function () {
var port = server.address().port;
});
io = require('socket.io')(server);
io.on('connection', function (client) {
console.log('Client connected...');
client.on('join', function (data) {
console.log(data);
});
});
//router.js
module.exports = function(getIOInstance){
router.route("/addmenu").post(function (req, res) {
menuModel.addMenu(req.body,function(data){
//I WANT EMIT HERE
getIOInstance().sockets.emit(...)
res.json(data)
});
};
return router;
);
This solution will work if you want to 'notify' all connected clients.
If you need to notify only a specific client, then I will advise you to use an event-emitter module in order to communicate these events and not share your socket instances across multiple files.
In router.js you can do something like:
//router.js
module.exports = function(io) {
var router = //What you declared it to be
router.route("/addmenu").post(function (req, res) {
menuModel.addMenu(req.body,function(data){
//I WANT EMIT HERE
res.json(data)
});
};
);
return router;
}
//server.js
//Change this line to be like the one below
var router = require('./app/router');
//.........
//.......
//Desired way
var router = require('./app/router')(io);
The answer of #jahnestacado does the job, but in case you already have an existing code base, then you need to change the structure of each file, where you might need the socket.io object, to pass it in as an argument.
A better way to do it then, would be:
To create the getIO() function—just as #jahnestacado did—, where you instantiate the io object (inside server.js), and export it.
var io;
exports.getIO = () => io;
Then require it wherever you need it. But make sure to execute the function only when you need it. Typically inside your controller function:
const getIO = require('../server').getIO;
exports.updateSAE = (req, res) => {
let io = getIO();
io.emit();
// rest of your controller function code
}
Note that I did not call the getIO function outside the controller function. For example, the following would probably not work:
const getIO = require('../server').getIO;
var io = getIO();
exports.updateSAE = (req, res) => {
io.emit();
// rest of your controller function code
}
Simply because the socket.io object could have not been initialized when you call the function, thus returning undefined.

how to emit.to a socket.io room from within express route

I have the following code structure:
/app.js
var user = require('./server/routes/api/user');
var io = require('socket.io').listen(server);
require('./server/sockets/base')(io);
I know I can emit events the following way (tested and works)
io.to("someroom").emit("news", "news");
Problem is, I want to be able to emit the event from my route file, which doesn't have access to the io object.
/routes/api/user.js
router.post('/login', function(req, res){
// HERE I WANT TO EMIT THE EVENT BY USING io.to("someroom").emit("news", "news");
// I TRIED req.socket.emit('news', { hello: 'world' }); without luck
}
What would be the easiest way to emit with this folder structure?
Your route needs the io object, so you'll have to pass it as a parameter.
In user.js:
module.exports = function (io) {
// all of this router's configurations
router.post('/login', function (req, res, next) {
io.to('someroom').emit('news', 'news');
});
return router;
}
When you use the route, give it a reference to io:
app.use(..., user(io));
const io = require('socket.io').listen(server);
app.set('io', io);
and then in the router
router.get('/', (req, res) => {
req.app.get('io').to('someroom').emit('news', 'news');
});
Just export the socket and require it in any file you want to use it from.
/socket.js
var server = require('./app.js');
var io = require('socket.io').listen(server);
module.exports = io;
/app.js
module.exports = server;
var user = require('./server/routes/api/user');
var io = require('./socket.js');
require('./server/sockets/base')(io);
/routes/api/user.js
var io = require('../../../socket.js');
router.post('/login', function(req, res){
io.to("someroom").emit("news", "news");
}

using object in another js file

I am getting my hands on node.js and I am trying to understand the whole require/exports thing. I have the following main app.js file:
/app.js
var express = require('express'),
http = require('http'),
redis = require('redis'),
routes = require('./routes'),
var app = express(),
client = redis.createClient();
// some more stuff here...
// and my routes
app.get('/', routes.index);
then, I have the routes file:
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
I can of course use the client object on my app.js file, but how can I use the same object in my routes?
Since req and res are already being passed around by Express, you can attach client to one or both in a custom middleware:
app.use(function (req, res, next) {
req.client = res.client = client;
next();
});
Note that order does matter with middleware, so this will need to be before app.use(app.router);.
But, then you can access the client within any route handlers:
exports.index = function(req, res){
req.client.get(..., function (err, ...) {
res.render('index', { title: 'Express' });
});
};
The easiest way is to export a function from your routes file that takes a client, and returns an object with your routes:
exports = module.exports = function (client) {
return {
index: function (req, res) {
// use client here, as needed
res.render('index', { title: 'Express' });
}
};
};
Then from app.js:
var client = redis.createClient(),
routes = require('./routes')(client);

Resources