Reputation: 134
I want to write a real-time chat application with socket.io and because my server and app file are separate, I kind of have no clue that how should I structure it to use socket.io instance in other parts of my app.
This is my app.js
file.
const express = require("express");
const pug = require("pug");
const app = express();
module.exports = app;
and this is my server.js
file
const app = require("./app");
const mongoose = require("mongoose");
mongoose
.connect(`mongodb://localhost:27017/${process.env.DATABASE}`)
.then(() => {
app.listen(process.env.PORT);
})
.catch((err) => {
console.error(`connection failed: ${err}`);
});
what is the best way to create an instance of socket.io and start it's connection for use in other parts of app?
Upvotes: 0
Views: 328
Reputation: 1042
You can use http with express app and then connect sockets through that http connection and you can listen and emit the topics inside the io.on('connection')
const app = require("./app");
const mongoose = require("mongoose");
const http = require('http').Server(app);
const io = require('socket.io')(http);
mongoose
.connect(`mongodb://localhost:27017/${process.env.DATABASE}`)
.then(() => {
app.listen(process.env.PORT);
io.on('connection', socket => {
console.log('socket connected',socket);
});
})
.catch((err) => {
console.error(`connection failed: ${err}`);
});
I will prefer this second way:
App.js
const express = require("express");
const pug = require("pug");
const app = express();
module.exports = app;
Server.js
const app = require("./app");
const realtime = require("./realtime");
const mongoose = require("mongoose");
const server = require("http").Server(app);
mongoose
.connect(`mongodb://localhost:27017/${process.env.DATABASE}`)
.then(() => {
app.listen(process.env.PORT);
require("./realtime.js")(server);
})
.catch((err) => {
console.error(`connection failed: ${err}`);
});
Realtime.js
module.exports = (app) => {
const io = require("socket.io")(app);
io.on("connection", (socket) => {
console.log("Socket connected")
})
};
Upvotes: 1