Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

node.js - Use socket.io inside a express routes file

I'm trying to use Socket.io with Node.js and emit to a socket within the logic of a route.

I have a fairly standard Express 3 setup with a server.js file that sits in the route, and then I have an index.js which sits in a routes folders that exports all the pages/publically accessible functions of the site. So they look like:

exports.index = function (req, res) {
    res.render('index', {
        title: "Awesome page"
    });
}; 

with the routing defined in server.js like:

app.get('/',routes.index);

I'm assuming I have to create the socket.io object in the server.js, since it needs the server object, but how can I access that object and emit to it from the index.js export functions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is a better way to do this now with Express 4.0.

You can use app.set() to store a reference to the io object.

Base configuration:

var app = require('express')();
var server = app.listen(process.env.PORT || 3000);
var io = require('socket.io')(server);
// next line is the money
app.set('socketio', io);

Inside route or middleware:

exports.foo = function(req,res){
    // now use socket.io in your routes file
    var io = req.app.get('socketio');
    io.emit('hi!');
}

Information about app.set() and app.get() is below:

app.set(name, value)

Assigns setting name to value. You may store any value that you want, but certain names can be used to configure the behavior of the server. These special names are listed in the app settings table.

Calling app.set('foo', true) for a Boolean property is the same as calling app.enable('foo'). Similarly, calling app.set('foo', false) for a Boolean property is the same as calling app.disable('foo').

Retrieve the value of a setting with app.get().

Source: https://expressjs.com/en/api.html#app.set


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...