const PORT = 3000;
const HOST = 'localhost';
var express = require('express'),
http = require('http'),
server = http.createServer(app);
var app = express();
const redis = require('redis');
const client = redis.createClient();
const io = require('socket.io');
if (!module.parent) {
server.listen(PORT, HOST);
const socket = io.listen(server);
socket.on('connection', function(client) {
const subscribe = redis.createClient()
subscribe.subscribe('realtime');
...
...
});
});
}
I stumbled upon this piece of code in one of the sites , In the above code I want to know the reason why the condition (!module.parent) is used ??? Whats the need for using it ??
If there is no module.parent it probably means that the module is being run on its own rather than being used in another program. If the !module.parent block is in a utility module I would guess that it is code for a test or developer tool. In a program that does stuff on it's own (e.g. a webserver), it would probably be the main entry point and the purpose of using it would be to make it possible to require components of that program without running the program.
Related
So I have this web application that is am moving to my personal website but I've been encountering a few errors and I haven't been able to find a solution for this one:
For some reason I get
polling.js:311 GET https://kayden.dev/socket.io/?EIO=4&transport=polling&t=O35Ebas 404
on the client side that appears every few seconds.
My code does need some cleaning up so I won't be showing everything but here. The server side code looks something like this:
const http = require('http');
const express = require('express');
const socket = require('socket.io');
const path = require('path');
let app = express();
let port = app.get('port');
let users = [];
let amountOnline = 0;
//send static files from public to the client
let server = app.listen(port, function(){
console.log('listening to requests on port '+ port);
});
//first parameter is the /whatever that goes after the url
app.use("/skyfighters", express.static(__dirname + '/public/'));
//setup socket
let io = socket(server);
io.serveClient(true);
And the client side code only has let socket = io.connect();
that actually executes at the moment with this error happening
Any help is appreciated, this is the first time I migrate a node app the a web server so I'm quite unfamiliar with it.
Thanks!
My express app logic is separated into a separate file from the instantiation of the express server, so I'm having issues with accessing socket.io within this app file. Should I just move the socket.io implementation into index.js or is it possible to keep that logic in app.js?
index.js
const http = require('http');
const app = require('./app');
const server = http.createServer(app);
const io = require('socket.io')(server);
const config = require('./utils/config');
const logger = require('./utils/logger');
app.set('socketio', io);
server.listen(config.PORT, () => {
logger.info(`Listening on port ${config.PORT}`);
});
app.js
const express = require('express');
const config = require('./utils/config');
const middleware = require('./utils/middleware');
const app = express();
app.use(middleware.requestLogger);
const io = app.get('socketio');
io.on('connection', (socket) => {
io.emit('test', { test: 'test' });
});
app.use(middleware.errorHandler);
module.exports = app;
You have a load order problem. You are loading app.js into index.js BEFORE you create and set io as an app property. So, when app.js tries to use the io property, it hasn't yet been set.
The way you have things split between the files, you've created a circular dependency. You can't create io until you've created the server, but you can't create the server until you have the app which is in app.js. So, you can't create io before you load app.js.
There are lots of ways around this. I find it kind of weird that you're creating the server in one file and the app object in another file since the two are fully required to make an operational server. So, I'd rearrange how those things are done like this:
// index.js
const http = require('http');
const app = require('express')();
const server = http.createServer(app);
const io = require('socket.io')(server);
app.set('socketio', io);
require('./app.js')(app);
const config = require('./utils/config');
const logger = require('./utils/logger');
server.listen(config.PORT, () => {
logger.info(`Listening on port ${config.PORT}`);
});
And, then modify app.js like this:
const config = require('./utils/config');
const middleware = require('./utils/middleware');
module.exports = function(app) {
app.use(middleware.requestLogger);
const io = app.get('socketio');
io.on('connection', (socket) => {
io.emit('test', { test: 'test' });
});
app.use(middleware.errorHandler);
}
There are 100 other ways to organize the code to fix this. Exporting a function that you can call and passing that function one or more arguments is one way to help control the timing of these circular dependencies.
I've recently gotten into socket.io, during a long-term project of mine. Which is probably why I am having such a hard time of it, because their "getting started" sections don't take into account you may already be deep into development of your own application. The main issue is it connecting, it won't do it, client-side that is.
I keep getting a 404 not found which is cause by CANNOT POST /socket.io/ Which it is right, it can't obviously, mainly because that is not where the socket.io location is (it is in node_modules per usual). Secondly if I create a route for this, it does absolutely nothing. So here is code initializing it:
/*jshint esversion: 6*/
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const path = require('path');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const db = require('./config/db');
// Init App
const app = express();
// Init http server
const server = http.createServer(app);
// init socket
const io = require('socket.io').listen(server);
Here is the clientside trying to connect to it:
if (window.location.hostname == 'playkog.net' || window.location.hostname == 'www.playkog.net') {
var port = 443;
} else {
var port = 8080;
}
var connected = false;
var socket = io.connect(window.location.hostname + ':' + port, { 'connect timeout': 5000 });
// Connection Successful
socket.on('connect', function () {
console.log('a user connected');
connected = true;
});
socket.on('disconnect', function () {
console.log('user disconnected');
connected = false;
});
I imagine I'll have to connect to a different port, however I'm not sure which, nor if that is my issue (or only issue). Of course be extremely new to this kind of stuff (amateur at best) some of these things just go right over my head.
Here is a screenshot of my console
Is there any difference between this implementation:
this.app = express();
this.httpServer = http.createServer(this.app);
this.io = socket.listen(this.httpServer);
And this one:
this.app = express();
this.server = http.createServer(this.app);
this.io = socket(this.server);
Nopers, the second is a shorthand. :)
The first is provided in the event that you want to import/export the function from your express architecture
It seems like your other question was posted after this, is this still relevant?
Ok let's see what I've done that worked. I have seperated my sockets into a config file because my app.js was getting cluttered.
app.use(express.static(path.join(__dirname, '/')));
app.use(express.static(path.join(__dirname, '/node_modules/')));
var clients = {};
var server = http.createServer(app);
var io = require('socket.io')(server);
require('./config/app.socket.js')(io);
server.listen(8001);
io.set("origins", "*:*");
So, I cut out the middleman and pass the server directly to the socket.io import. then, I pass the reference to that io server to my app.socket.js file and listen to the server on port 8001
Here is my app.socket.js initialization
module.exports = function(io){
var clients = {};
var sockets;
io.on('connection', function (socket) {
sockets = socket;
socket.on(//your socket function)
}
I have discovered that there are at least 2 ways to go about doing this. The first way creates an HTTP server, although the 2nd way doesn't.
I am not able to find any concrete tutorial regarding this.
Case I
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(3000);
Case II
var app = require('express')();
var port = process.env.PORT || 3000;
var io = require('socket.io').listen(app.listen(port));
How are the two methods different? And why doesn't the second method require an HTTP server?
app.listen() creates the http server for you (a shortcut that express lets you use).
Here's the code for app.listen():
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
This Express code is here.