Nodejs include socket.io in router page - node.js

I have an express node app, and I'm trying to keep my code neat by not having all the socket.io stuff in app.js
I don't know the best way to go about this. Here is my initial thought which doesn't feel like the cleanest one
// app.js
var express = require('express')
, app = express()
, server = require('http').createServer(app)
, url = require('url')
, somePage = require('./routes/somePage.js')
, path = require('path');
app.configure(function(){...});
app.get('/', somePage.index);
and the route
// somePage.js
exports.index = function (req, res, server) {
io = require('socket.io').listern(server)
res.render('index',{title: 'Chat Room'})
io.sockets.on('connection', function(socket) {
...code...
}
}
I feel like I'm close but not quite there

I don't know if I'm reading that right but it looks like you are starting a socket server on every request for /, which I'm frankly a little surprised works at all.
This is how I'm separating out the socket.io code from app.js (using express 3.x which is a bit different than 2.x):
// app.js
var express = require('express');
var app = express();
var server_port = config.get('SERVER_PORT');
server = http.createServer(app).listen(server_port, function () {
var addr = server.address();
console.log('Express server listening on http://' + addr.address + ':' + addr.port);
});
var sockets = require('./sockets');
sockets.socketServer(app, server);
// sockets.js
var socketio = require('socket.io');
exports.socketServer = function (app, server) {
var io = socketio.listen(server);
io.sockets.on('connection', function (socket) {
...
});
};
Hope that helps!

a similar approach is to pass app into index.js file and initiate http and socketio server there.
//app.js
//regular expressjs configuration stuff
require('./routes/index')(app); //all the app.get should go into index.js
Since app is passed into index.js file, we can do the app.get() routing stuff inside index.js, as well as connecting socketio
//index.js
module.exports = function(app){
var server = require('http').createServer(app)
,io = require('socket.io').listen(server);
app.get('/', function(req, res){
});
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
io.sockets.on('connection', function(socket){
socket.on('my event', function(data){
console.log(data);
});
});
io.set('log level',1);
//io.sockets.emit(...)

Related

SocketIO emit won't fire inside express route

The following works fine, I can get the http response on my client app BUT the socketio emit doesn't seem to work. I have no idea why it is not firing.
Here's my code (some parts removed):
app.js
var express = require('express');
var port = process.env.PORT || 3000;
var socketio = require('socket.io');
var app = express();
var server = require('http').Server(app);
var io = socketio(server);
var beacons = require('./routes/beacons')(io);
app.use('/beacons', beacons);
server.listen(port, () => {
console.log('Listening on port '+port);
});
io.on('connection', (socket) => {
socket.on('beacon:show', function(data) {
console.log('Show beacon: ' + data)
socket.broadcast.emit('beacon:draw', data)
})
});
module.exports = app;
beacons.js
var express = require('express');
var router = express.Router();
module.exports = function(io) {
router.get('/buy', function(req, res) {
io.emit('beacon:show', {data: someData}) // Not Firing
res.json({success: true})
})
return router
}
You need to wrap your io.emit() inside an io.on('connection', => {}).
At the moment, you are sending in just the io variable, but every single request and emission needs to be wrapped inside a connection event. Otherwise how does socket.io know who it's sending it to, or if there's even anyone to send it to?
This can only really be done inside beacons.js and the router.get('/buy') section, because having it the other way around (a route wrapped inside a connection) won't work.

What does require('express')() do in NodeJS

As far as I understand, require('express')() doesn't create a server, it just bundles the functions together. But if so, how does the following code run without server?
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
Also, if it does create a server, why do I need to import http module and manually create a server in the following example?
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
I am very confused. Thanks in advance.
require('express')() creates an instance of an Express application.
It's short for this:
var express = require('express');
var app = express();
You don't need to explicitly use http if you want to create an HTTP server, because Express will create one for you if you call app.listen().
If you need that server for something else, for instance, to attach a socket.io instance to, you can use this:
var express = require('express');
var app = express();
var server = app.listen(3000, ...); // returns an `http.Server` instance
var io = require('socket.io')(server);
Basically when you do require('express'), it imports a function. The following () calls the function as well. Basically it instantiates an express app.

access application port : express

I am trying to build a simple chat application with node.js using Express.My node version is v0.12.7 and express version is 4.13.1.
I need to access the port the application is listening to but I am not getting how to do that even after lot of research over google.
My code in index.js is:
var express = require('express');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
io.on('connection', function(socket){
console.log('a user connected');
});
console.log(app.get('port')); // not working
http.listen(app.get('port'), function(){
console.info('Server listening on port :');
});
module.exports = router;
Please suggest If this can be done and how. Thanks in advance :)
In order to get the port, you're going to have to set it first like this
var app = require('express')();
app.set('port', process.env.PORT || 3000);
...

Access the public folder when using node and Express?

I have looked through stackoverflow and read the express documentation, I can't figure out why the app won't run when I implement "app.use(express.static());" does anyone know a fix?
var express = require('express')();
var app = require('express')();
var server = require('http').Server(app);
var io = require("socket.io").listen(server);
//If i use this my app will not start
// app.use(express.static());
app.get('/', function(req, res){
res.sendfile('index.html');
});
//Get input from front-end
io.on('connection', function(socket){
// On input do something
socket.on('directional in', function(unique_id, input, input1){
// send info to index
io.emit('directional out', unique_id, input, input1);
});
});
server.listen(3000, function(){
// Server is running
console.log('listening on *:3000');
});
Any help would be great!
You're not initialising express correctly. The correct way would be as follows:
var express = require('express');
var app = express();
With this, you will be able to do
app.use(express.static(__dirname + '/public'));
All together, a fully functional express app would look like this in its most basic form:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(process.env.PORT || 3000);
Let me know what happens.

Socket.io and Express3 - 404 on client request to /socket.io/socket.io.js

I am receiving a 404 when trying to resolve '/socket.io/socket.io.js' from my Node server. I can't determine why.
My server configuration looks like this:
var express = require('express')
, engine = require('ejs-locals')
, app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
// use ejs-locals for all ejs templates:
app.engine('ejs', engine);
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs'); // so you can render('index')
app.use(express.static(__dirname + '/public'));
//define routes
...
app.listen(3000);
//socket io
io.sockets.on('connection', function (socket) {
socket.on('set nickname', function (name) {
socket.set('nickname', name, function () {
socket.emit('ready');
});
});
socket.on('msg', function () {
socket.get('nickname', function (err, name) {
console.log('Chat message by ', name);
});
});
});
At the client I have this:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
I am testing this locally (port: 3000). The Socket code is basically ripped off of the socket.io example to get something working. I have reviewed other posts and can't seem to find where I'm going wrong. Can someone help?
Thanks
Got it!
The HTTP server needs to be listing on the port (3000 in this case.) I then removed the app.listen(3000) as the address will already be in use and is not needed.
Thanks!
var express = require('express')
, engine = require('ejs-locals')
, app = express()
, http = require('http')
, server = http.createServer(app).listen(3000)
, io = require('socket.io').listen(server);

Resources