如何在使用socket时在nodejs中导入代码?

时间:2017-07-06 13:20:38

标签: node.js express

目前我正在尝试这种方式:

io.sockets.on('connection', function (client) {
    console.log("client connected: " + client.id);
    io.sockets.socket(client.id).emit("connected", client.id);
    client.on("sendMessage", function (data) {
        //send message code 
    });
});

我想要的sendMessage代码应该在单独的文件中。那该怎么办?

我尝试了什么:

//in first.js:
var events = require('events');
var em = new events.EventEmitter();
var msg = require('./message.js');
var emitter = msg.em;

io.sockets.on('connection', function (client) {
    console.log("client connected: " + client.id);
    io.sockets.socket(client.id).emit("connected", client.id);
    emitter.emit('sendMessage');
});


//in message.js

client.on("sendMessage", function (data) {
    //return "Hello";
    //perform db operation
});

是正确还是错误?有人可以帮忙吗?         或者有任何新的正确方法吗?

1 个答案:

答案 0 :(得分:0)

您可以将处理程序放在其他文件中并导出它。

主要代码:

const sendMessage = require('./send-message');

io.sockets.on('connection', function (client) {
    console.log("client connected: " + client.id);
    io.sockets.socket(client.id).emit("connected", client.id);
    client.on("sendMessage", sendMessage);
});

发送-message.js:

module.exports = function (data) {
    //send message code 
});