如何通过Socket.IO将数据从另一个文件发送到客户端?

时间:2018-10-16 08:06:40

标签: node.js express socket.io

file2.js中有一个函数可以创建一些数据。此数据应转到file1.js,并应从那里发送到客户端。我该怎么办?

app.js:

var app    = express();
var server = require('http').createServer(app);
var io     = require('socket.io')(server);
var file1  = require('./file1')(io);

file1.js:

var file2 = require('./file2');

//This is how it usually works if I want to interact with a client:
module.exports = function(io) {
  io.on('connection', function (socket) {
    socket.on('channel_x', function (data, callback) {});
  });
}

//What if I want to send (emit) data which comes from another file to the client?
exports.functionInFile1 = function(exampleDataFromFile2) {
  //How to send "exampleDataFromFile2" to client from here?
}

file2.js:

var file1 = require('./file1');

function functionInFile2() {
  //do something
  var exampleData = {some: "data"};
  file1.functionInFile1(exampleData);
}

functionInFile2();

1 个答案:

答案 0 :(得分:0)

为什么不像io一样向file2提供file1实例,然后再从那里本身向客户端发送数据。

file2.js

function functionInFile2(io) {
    //do something
    var exampleData = { some: "data" };
    io.emit('message', exampleData);
}

module.exports = functionInFile2;

file1.js

var functionFile2 = require('./file2');

module.exports = function(io) {
    io.on('connection', function(socket) {
        socket.on('channel_x', function(data, callback) { });
    });
    functionFile2(io);
}