如何将变量从app.js导出到Node js中的另一个路径

时间:2014-11-04 17:42:52

标签: node.js express socket.io

我在我的节点项目中使用socket.io并想知道如何导出io变量

这是我到目前为止所做的,但是我收到了这个错误:Object #<Object> has no method 'on'

app.js中的

        var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index')(io);
var users = require('./routes/user');

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(4000);

require('./routes/index')(io);

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

// app.use(favicon(__dirname + '/public/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err,
            title: 'error'
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {},
        title: 'error'
    });
});
/*
io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});
*/

module.exports = app;
index.js中的

var io = require('../app');

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

我想导出变量的原因是我不必定义io就像我在app.js中所做的那样是index.js,这导致我基本上定义了服务器和app变量!

我只想在index.js路由中执行所有socket.io内容(除了必须重新定义index.js中的app,server和io变量)!

希望我已经解释了我的自我

谢谢!

3 个答案:

答案 0 :(得分:9)

您的依赖项未正确设置。您正在初始化io之前执行index.js

var routes = require('./routes/index');
/* index.js starts being executed at this point
 * hence, io is undefined inside index.js
 */

相反,为什么不尝试

<强> app.js

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(4000);
module.exports = io;

var routes = require('./routes/index');
var users = require('./routes/user');

<强> index.js

 var io = require('../app');

io.on('connection', function (socket) {
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
    console.log(data);
    });
});

答案 1 :(得分:1)

我认为你需要使用套接字。

io.sockets.on('connection', ... ); 

答案 2 :(得分:0)

它看起来像一个循环依赖(app.js需要index.js和index.js需要app.js)

试试这个。

将app.js更改为:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var users = require('./routes/user');

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(4000);

require('./routes/index')(io);

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

// app.use(favicon(__dirname + '/public/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/users', users);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err,
      title: 'error'
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {},
    title: 'error'
  });
});
/*
 io.on('connection', function (socket) {
 socket.emit('news', { hello: 'world' });
 socket.on('my other event', function (data) {
 console.log(data);
 });
 });
 */

module.exports = app;

将index.js更改为:

module.exports = function(io){
  io.on('connection', function (socket) {
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
      console.log(data);
    });
  });
}