Using SocketIO in external lib for expressjs - javascript

my app.js is started with following code
var express = require("express"),
app = express(),
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server),
games = require("./lib/games");
Now I need to use socket.io in external lib which named games,how can I do that?

There are many ways to do this. One way is to have games export a function which accepts the socket.io object as a parameter.
For example:
// games.js
module.exports = function(io) { ... /* do something with io */ }
// app.js
var io = require('socket.io').listen(server),
games = require("./lib/games");
games(io);

Related

Cannot connect socket.io to frontend javascript file

I am developing a website that needs to catch events emitted from server.js into a javascript file that handles the frontend. Obviously I am using socket.io (i said that in the title) and the method I am using to connect the backend and the frontend is the following:
<script src="/socket.io/socket.io.js"></script>
<script src="js/chat.js"></script>
Then in the chat.js file i just decalre a const like this:
const socket = io();
and then I use the method
socket.on('event', (data) =>{
});
eccc...
This method does not seem to work though.
It says: Failed to load resource: the server responded with a status of 404 (Not Found).
(Also says that io is not defined but it's normal if it cannot find the socket.io file).
I have followed a tutorial that has done the same and it does not work anymore as well.
On my server.js the code looks like this:
const mongoose = require('mongoose');
const connectDB = require('./config/dbConnection');
const express = require('express');
const app = express();
const path = require('path');
const http = require('http');
const server = http.createServer(app);
const socketio = require('socket.io');
const io = socketio(server);
const fsPromises = require('fs').promises;
const bodyParser = require('body-parser');
const User = require('./model/user');
const moment = require('moment');
const PORT = process.env.PORT || 3500;
Thanks to anyone who answers.

How to use socket.io across diffrent routes in node.js

I have different routes in my node js application and i have to use socket.io in every route to make my node and react js application realtime. But, i have the below structure of my node js application.
router.js
const express = require('express');
const router = express.Router();
const worksheetController = require('../controllers/worksheet')
const attendenceController = require('../controllers/attendence')
router.route('/worksheets')
.get(
worksheetController.getWorksheet
)
.post(
worksheetController.validateWorksheet,
worksheetController.addWorksheet,
attendenceController.markAttendence
)
router.route('/attendances')
.get(
attendenceController.getAttendance
)
module.exports = router;
server.js
const express = require('express');
const router = require('./router');
const app = express();
app.use('/api', router);
app.listen('5000', () => {
console.log('Listening on port');
});
module.exports = app;
So, I want to know
1) Should i need to use http module to create a server, if i need to use socket.io.
2) How can i use socket.io for diffrent routes.
I found posts that match's to my question on stackoverflow, which is this, this and this. But i don't think, that works for me. So please help me.
You can use http module or other module in document of socket.io for to use socket.io
I don't sure your idea. But when you want implement socket.io. I think you should run another node app. (Meaning you have 2 nodejs app. 1 for node http normally and 1 for socket.io app). After you can use path option when init socket.io app https://socket.io/docs/server-api/#new-Server-httpServer-options. Because when you deploy to production. You should run your socket.io app with beside of proxy serve (ex: nginx). Socket.io basically support multi transport and protocol. So if use with http restful. How about config your connection mapping from nginx to socket.io app, how you setup error handler ?.
In your case:
+ Create new file socket.js:
// socket.js
var http = require('http')
var socket_io = require('socket.io')
function init_socket(app) {
const server = http.Server(app)
const io = socket_io(server, { path: 'your-path-want-for-socket-io' }) // default: /socket.io/
}
import {init_socket} from 'socket.js'
init_socket(app)

massive.connectSync not a function

Why do I get this error, massive.connectSync is not a function when I run server.js. It works on my mac, but not my windows. Please help solve this enter code hereerror
var express = require("express");
var app = express();
var http = require('http');
var massive = require("massive");
var connectionString = "postgres://massive:#localhost/MarketSpace";
// connect to Massive and get the db instance. You can safely use the
// convenience sync method here because its on app load
// you can also use loadSync - it's an alias
var massiveInstance = massive.connectSync({connectionString : connectionString})
// Set a reference to the massive instance on Express' app:
app.set('db', massiveInstance);
http.createServer(app).listen(8080);
Synchronous functions are no longer supported, and the connect function itself no longer exists, it's all promises all the way:
var express = require("express");
var app = express();
var http = require('http');
var massive = require("massive");
var connectionString = "postgres://massive:#localhost/MarketSpace";
massive(connectionString).then(massiveInstance => {
app.set('db', massiveInstance);
http.createServer(app).listen(8080);
});
Note that massive requires node > 6. If you are using and older version you'll need to update node in order to use massive.
Docs

Node.js: require() and passing variables

Started a project with npm which created a certain file structure:
www <-- require() calls app.js; instantiates server
app.js <-- instantiates var app = express(); and has module.exports = app;
Now, I'd like to use sockets.io. In my 'www' file, here is a code snippet:
var app = require('../app');
...
var server = http.createServer(app);
And I'd like to put all of my server-side socket listeners in app.js, but the following code:
var io = require('socket.io').listen(server);
requires server as an input. How do I make the server I instantiated in 'www' accessible in 'app.js'?
It seems a little strange. But if you insist on such a structure than you can export an object from www that will have app as it's property and a method that binds socket listeners an receives app object as a param.
module.exports = {
app: app,
bindSocketListeners: function(server, io) {
io.listen(server);
return io;
}
};
And call it:
var appObj = require('../app');
var io = require('socket.io');
var app = appObj.app;
var server = http.createServer(app);
io = appObj.bindSocketListeners(server, io)

Should modules be configured with app.use in all routes at express.js?

I was told that if I want to use one same express module in different route files the proper way of doing it would be to include it in every route file rather than making it globally in app.js.
Now I'm wondering if I should duplicate all the app.use as well in all of them or if I should only do it once in app.js.
In case of doing it in app.js, then I should include all those modules as well in app.js duplicating yet more code. Am I right?
To illustrate it a bit better I'll add the following example:
/* routes/users.js
-----------------------------------------------------*/
var express = require('express');
var app = express();
var http = require('http')
var server = http.Server(app);
var io = require('socket.io')(server);
var path = require('path');
var swig = require('swig');
var request = require('request');
//for ZMQ
var cluster = require('cluster');
var zmq = require('zmq_rep');
//for FORMS
var bodyParser = require('body-parser');
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use( bodyParser.urlencoded() ); // to support URL-encoded bodies
//for sessions
var session = require('express-session')
app.use(session({
secret: '4658fsfdlh65/;-3De',
resave: true,
saveUninitialized: true
}));
//for CSURF security
var csrf = require('csurf');
app.use(csrf());
//for security
var helmet = require('helmet');
app.use(helmet());
What I understood is that I have to duplicate the following includes in every route I need to use them, having any of those files initial content like this:
var express = require('express');
var app = express();
var http = require('http')
var server = http.Server(app);
var io = require('socket.io')(server);
var path = require('path');
var swig = require('swig');
var request = require('request');
//for ZMQ
var cluster = require('cluster');
var zmq = require('zmq_rep');
//for FORMS
var bodyParser = require('body-parser');
//for sessions
var session = require('express-session')
//for CSURF security
var csrf = require('csurf');
//for security
var helmet = require('helmet');
What about app.use then?
No you don't have to duplicate app.use and module includes in other routes files and you can do it in app.js only.
You only have to include modules whichi you want to use in the route file.
e.g.
var bodyParser = require('body-parser');
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use( bodyParser.urlencoded() ); // to support URL-encoded bodies
this should be done only once in the application and you don't have to repeat it in routes files.
In the link provided by you, you had to include the request module because you want to use the module in that file.
I would advise you to go through any sample node-express app to have good understanding of organising the code. e.g. https://github.com/madhums/node-express-mongoose-demo/

Categories