Reputation: 3636
I am using Socket.io for real time image upload process but I got this error mentioned below. I'm writing socket and app.js logics in different files by referring this answer now i want to emit that socket events in controller files but got the error
UnhandledPromiseRejectionWarning: TypeError: io.emit is not a function
below is my code
app.js
// modules =================================================
var express = require('express');
var app = express();
const logger = require('morgan');
var bodyParser = require('body-parser');
const indexRouter = require("./routes/index");
const cors = require('cors');
const path = require("path");
const config = require("./environments/index");
var http = require('http').Server(app);
var sockets = require('./apis/socket.io');
// configuration ===========================================
var port = config.PORT || 8081; // set our port
sockets.getSocketIo(http);
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true,
parameterLimit: 50000
}));
app.use(cors());
app.use(logger('dev'))
app.use("/api", indexRouter);
app.use(express.static(path.join(__dirname, "/build")));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
http.listen(port, () => {
console.log('Magic happens on port ' + port); // shoutout to the user
});
exports = module.exports = app;
This is socket.io.js
file code
var socketio = require('socket.io');
var io = {};
module.exports = {
getSocketIo: function (app) {
let userId = 1
io = socketio.listen(app);
io.sockets.on('connection', function (socket) {
console.log("new connection: " + socket.id);
console.log(socket)
console.log('socket connected')
// let rooms = socket.id
io.sockets.adapter.rooms
if (io.nsps['/'].adapter.rooms["room-" + userId] && io.nsps['/'].adapter.rooms["room-" +
userId].length > 0) userId++;
socket.join("room-" + userId);
//Send this event to everyone in the room.
io.sockets.in("room-" + userId).emit('connectToRoom', "You are in room no. " + userId);
io.sockets.in(userId).emit('Image_upload', "Image uploading is started");
console.log(socket.room)
console.log(socket)
});
}
};
This is controller code of api controller
report_data: async (req, res) => {
if (!req.body.id) {
logger.warn(error.MANDATORY_FIELDS);
return res.status(500).send(error.MANDATORY_FIELDS)
}
io.emit('progress', "Image is Uploading started Please Wait A minute");
io.emit('error', "clients connected!");
let Id = req.body.id;
let path = `tmp/daily_gasoline_report/${Id}`;
req.body.data_url = path
sequelize.sequelize.transaction(async (t1) => {
let result = error.OK
result.data = data
logger.info(result);
return res.status(200).send(result)
}).catch(function (err) {
logger.warn(err);
console.log(err)
return res.status(500).send(error.SERVER_ERROR)
})
},
Upvotes: 1
Views: 210
Reputation: 26
You can Make changes like below in your file
app.js
// modules =================================================
var express = require('express');
var app = express();
const logger = require('morgan');
var bodyParser = require('body-parser');
const cors = require('cors');
const path = require("path");
const config = require("./environments/index");
var http = require('http').Server(app);
var io = require('socket.io').listen(http);
const indexRouter = require("./routes/index");
// configuration ===========================================
var port = config.PORT || 8081; // set our port
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true,
parameterLimit: 50000
}));
app.use(cors());
app.use(logger('dev'))
app.use("/api", indexRouter);
app.use(express.static(path.join(__dirname, "/build")));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
http.listen(port, () => {
console.log('Magic happens on port ' + port); // shoutout to the user
});
app.locals.io = io
exports = module.exports = app;
socket.io.js
let io;
const getSocketIo = (http) => {
let userId = 1
io = require('socket.io')(http);
io.sockets.on('connection', function (socket) {
io.sockets.adapter.rooms
if (io.nsps['/'].adapter.rooms["room-" + userId] && io.nsps['/'].adapter.rooms["room-" + userId].length > 0) userId++;
socket.join("room-" + userId);
//Send this event to everyone in the room.
io.sockets.in("room-" + userId).emit('connectToRoom', "You are in room no. " + userId);
console.log("new connection: " + socket.id);
console.log('socket connected')
});
}
module.exports = {
getSocketIo,
io
};
in your controllers add this code in api you have mentioned whenever you want to use socket add this code before using it
const io = req.app.locals.io;
Upvotes: 1