简体   繁体   English

ReferenceError:在NodeJS中未定义io

[英]ReferenceError: io is not defined in NodeJS

I have a NodeJS project and need one of the variable defined in my app.js file in another file, this is possible? 我有一个NodeJS项目,并且需要另一个文件中我的app.js文件中定义的变量之一,这可能吗?

My code 我的密码

app.js app.js

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

otherFile.js 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'});
    });
  });

});

the error that I get in this case is TypeError: Cannot read property 'sockets' of undefined 我在这种情况下得到的错误是TypeError: Cannot read property 'sockets' of undefined

Blockquote 块引用

When you do: 当您这样做时:

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

You just create a local variable, that is visible only within the scope of that file. 您只需创建一个局部变量,该局部变量仅在该文件的范围内可见。

If you want to get access to it from another file using app.io after just importing app , you need to: 如果您想在导入app之后使用app.io从另一个文件访问它,则需要:

  • add io as a property of your app: io添加为应用程序的属性:

     app.io = io; 

or simply combine both: 或简单地将两者结合起来:

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

from the socket.io docs this should work: 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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM