我已经看到了几个引用这个问题的问题,但是无法实现这一点。
我有一个为API路由和套接字实时应用程序运行快速的应用程序。
我想保持我的server.js文件“干净”,并将所有与套接字相关的事件放在一个单独的文件中。我还希望能够从我的路径文件中激活一个事件。
我的server.js喜欢这样:
const dotenv = require('dotenv/config');
const express = require('express');
const bodyParser = require('body-parser');
const socketIO = require('socket.io');
var http = require('http');
const _ = require('lodash');
const path = require('path');
const publicPath = path.join(__dirname, '../public');
var {mongoose} = require('./db/mongoose');
var {ObjectID} = require('mongodb');
var {authenticate} = require('./middleware/authenticate');
var {socketEvents} = require('./middleware/socketEvents')(io);
var multiparty = require('connect-multiparty'),
multipartyMiddleware = multiparty();
var app = express()
var serv = require('http').createServer(app)
var io = socketIO.listen(serv)
var PORT = process.env.PORT || '80';
app.use(bodyParser.json());
app.use(multipartyMiddleware);
app.use(express.static(publicPath));
serv.listen(PORT, () => {
console.log('Started on port: ' + PORT);
});
module.exports = {
app
};
我想要一个包含以下内容的socketEvents.js文件:
io.on('connection', (socket) => {
console.log('New user connected');
//all socket events here
});
我怎样才能做到这一点?
答案 0 :(得分:0)
您可以测试以下模式:
server.js
'use strict';
const io = require('socket.io')(3000);
const io_logic = require('./socketEvents')(io);
console.log('socket.io server started at port 3000');
socketEvents.js
function socket_events (io) {
io.on('connection', function (socket) {
console.log('a client has connected');
});
}
module.exports = socket_events;