pass socket.io to router module in node js

ε祈祈猫儿з 提交于 2020-08-11 01:39:31

问题


snippet below is clear

// app.js
const express = require('express');
const app = express();

const http = require('http').createServer(app);
const io = require('socket.io')(http); 

const studentRouter = require('./routes/student')
app.use('/students', studentRouter)

but here

app.use('/students', studentRoute)

I want to pass io to studentRouter , How can I do that ?

and this is my studentRouter :

// student route 
const express = require('express');
const router = express.Router();


router.route('/').get((req, res, next) => {
    res.send("hi")
})

module.exports = router;

回答1:


You can change studentRouter to export a function that you can call and pass io to it:

const studentRouter = require('./routes/student')(io);

Then, inside the studentRouter file, instead of exporting the router directly, you export a function:

module.exports = function(io) {

  // define your router and set it up
  // you can then use io in your routes here

  return router;

}

When you export a single function like this from a module, it is often called a "module constructor" and it allows you to pass arguments that the module can then use when setting itself up. You just put the module's contents inside the function and it can then use the arguments in all of its code.



来源:https://stackoverflow.com/questions/61578047/pass-socket-io-to-router-module-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!