i have declared the io in the index.js file ( main file. and i want to emit the updates to the client inside the controllers/devices.js. but on testing it is is giving
TypeError: io.emit is not a function
at handleUpdateDevice (/home/parthkamal/Documents/development/tekuncorked-server/controllers/device.js:84:12)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
(node:98489) Warning: Accessing non-existent property 'emit' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)
node:internal/errors:496
ErrorCaptureStackTrace(err);
^
controllers/devices.js
const Device = require('../models/device');
const io = require('../index');
// other functions
const handlePostDevice = async (request, response) => {
try {
const { name, location, temperature } = request.body;
console.log(request.body);
console.log({ name, location, temperature });
const newDevice = new Device({ name, location, temperature });
await newDevice.save();
response.status(200).json({ message: "device added successfully" });
const devices = await Device.find();
io.emit('data-created', { devices });
} catch (error) {
console.log(error);
response.status(400).json({ error });
}
}
const handleUpdateDevice = async (request, response) => {
try {
const { id } = request.params;
const updates = request.body;
console.log(updates);
await Device.findByIdAndUpdate(id, updates);
response.status(200).json({ message: "updated successfully" });
const devices = await getDevices();
io.emit('data-updated', { devices });
} catch (error) {
console.log(error);
response.status(400).json({ error });
}
}
module.exports = {
getDevices,
handleGetDevices,
handleGetDevicesById,
handlePostDevice,
handleUpdateDevice
}
my directory structure is like this
index.js
const express = require('express');
const http = require('http');
const cors = require('cors');
const dotenv = require('dotenv');
const { getDevices } = require('./controllers/device')
const createDbConnection = require('./db');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: "http://localhost:3000",
}
});
dotenv.config();
const PORT = process.env.PORT;
const corsOptions = {
origin: 'http://localhost:3000',
};
//middlewares
app.use(cors(corsOptions));
app.use(express.json());
//routes
const deviceRoute = require('./routes/device');
app.use('/device', deviceRoute);
io.on('connection', async (socket) => {
console.log(`user with socket id ${socket.id} is connected`);
try {
const devices = await getDevices();
socket.emit('data', { devices });
} catch (error) {
console.log('connection ke dauran devices fetch karne me error agya');
}
socket.on('disconnect', () => {
console.log('a user got disconnected');
});
});
//db connection
createDbConnection();
app.get('/', (req, res) => {
res.send('hello from the tekuncorked server');
});
server.listen(PORT, () => {
console.log(`server is listening on port ${PORT}`);
});
module.exports = io;
i think there is a problem in exporting the io module. to the controller. how can I achieve that?