将Socket.io分离为app.js

时间:2018-06-27 01:06:41

标签: node.js sockets express socket.io

我正在正确处理Express项目,目前我有app.js,socket文件夹在哪里,但是我的所有逻辑都在bin / www中,因为我在这样的路由中使用了套接字:

 req.io.emit('dataUpdated', { id: client });

但是我想将其分离到app.js中,如何在不破坏我的应用程序的情况下做到这一点。

这是我的www文件:

var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var config = require('../config.json');
var appRoutes = require('./routes/Approutes');


var app = express();

app.use(express.static(path.join(__dirname, '../public')));

mongoose.Promise = global.Promise;
mongoose.connect('localhost/db_test');

app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'hjs');

app.set('appProperties', {
  secret: config.secret
});

var siofu = require("socketio-file-upload");
app.use(siofu.router);


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));


var debug = require('debug')('express-seed:server');
var server = require('http').Server(app);

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Set socket
 */

var socketioJwt = require('socketio-jwt');
var socketIo = require('socket.io');
var io = socketIo.listen(server);


io.use(socketioJwt.authorize({
   secret: config.secret,
   handshake: true
}));

app.io = io;
app.use(function(req, res, next) { 'use strict'; req.io = io; next(); });


app.use('/', appRoutes);



require('../sockets/user')(io);


/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);


/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

我的app.js文件为空... 和我的套接字文件

exports = module.exports = function (io) {
 io.sockets.on('connection', (socket) => {
   socket.on('clientGetList', (req) => {
// getting clientList
});
})
}

如何在不破坏应用程序的情况下将逻辑从www文件迁移到app.js文件?

1 个答案:

答案 0 :(得分:1)

  

我想将中间件和套接字连接移至app.js和www中,以启动服务器

您可以这样分离代码,并将appserver变量都传递到app.js模块,在该模块中,它可以运行其余的初始化代码(中间件,路由,套接字)。 io设置等...):

// www
const express = require('express');
const app = express();

const server = require('http').Server(app);

const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

// load app.js and let it do it's part of the initialization of app and server
require('./app.js')(app, server);

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);


/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

然后,这将是app.js的概述:

const bodyParser = require('body-parser');
const siofu = require("socketio-file-upload");
const config = require('../config.json');
const appRoutes = require('./routes/Approutes');
const socketioJwt = require('socketio-jwt');
const socketIo = require('socket.io');

// export one function that gets called once as the server is being initialized
module.exports = function(app, server) {
    app.set('views', path.join(__dirname, '../views'));
    app.set('view engine', 'hjs');

    app.set('appProperties', {
      secret: config.secret
    });

    app.use(siofu.router);


    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));    

    var io = socketIo.listen(server);


    io.use(socketioJwt.authorize({
       secret: config.secret,
       handshake: true
    }));

    app.io = io;
    app.use(function(req, res, next) { 'use strict'; req.io = io; next(); });


    app.use('/', appRoutes);

    require('../sockets/user')(io);

}