ReferenceError:io在NodeJS中没有定义

我有一个NodeJS项目,需要在另一个文件中的我的app.js文件中定义的variables之一,这是可能的?

我的代码

app.js

var app = express(); var io = require('socket.io').listen(app); ... 

otherFile.js

 var models = require('../models'); var express = require('express'); var path = require('path'); var fs = require("fs"); //To-Delete var recursive = require('recursive-readdir'); var router = express.Router(); var app = require ('../app.js'); // creating a new websocket to keep the content updated without any AJAX request app.io.sockets.on('connection', function(socket) { fs.watchFile(__dirname + '../README.md', function(curr, prev) { // on file change we can read the new xml fs.readFile(__dirname + '../README.md', function(err, data) { if (err) throw err; // parsing the new xml data and converting them into json file // var json = parser.toJson(data); // send the new data to the client socket.volatile.emit('notification', {message: 'el archivo cambio'}); }); }); }); 

在这种情况下得到的错误是TypeError: Cannot read property 'sockets' of undefined

大段引用

从socket.io文档这应该工作:

 var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); io.sockets.on('connection', function(socket) { // ... your code }); 

当你这样做时:

 var io = require('socket.io').listen(app); 

您只需创build一个局部variables,该variables仅在该文件的范围内可见。

如果您想在导入app后使用app.io从另一个文件访问它,则需要:

  • 添加io作为你的应用程序的属性:

     app.io = io; 

或简单地结合两者:

  app.io = require('socket.io').listen(app); 
  • 当然,导出应用程序本身