B
B
BEKa T2022-04-16 18:04:54
Node.js
BEKa T, 2022-04-16 18:04:54

How to export socket.io module for use in other files (routes)?

How to export socket.io module for use in other files (routes)? App.js
module export examplemysql

// mysql
const db = require('./db');

let sql = `SELECT * FROM users WHERE login LIKE '${login}'`;
db.query(sql, (err, result) => {
  if (err) throw err;
  if (result) {
    console.log(result);
    res.json({
      ok: true
    });
  }
});

db.js
const mysql = require('mysql');

// Connect to DB
const db = mysql.createConnection({
  host: "localhost",
  user: "root",
  database: "mytable",
  password: "",

  multipleStatements: true
});

db.connect(function(err) {
  if (err) throw err;
  console.log("MySQL Connected!");
});

module.exports = db;


As you can see. I can export the "db" module to any file in my project and use it there. Here I want the same with socket.io. Something like this
app.js
const io = new Server(server);

module.exports = io;


messages.js
const io = require('/routes/app');

io.on('connection', (socket) => {
  socket.on('chat message', msg => {
    io.emit('chat message', msg);
  });
});

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question