簡體   English   中英

ReferenceError:在NodeJS中未定義io

[英]ReferenceError: io is not defined in NodeJS

我有一個NodeJS項目,並且需要另一個文件中我的app.js文件中定義的變量之一,這可能嗎?

我的密碼

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

塊引用

當您這樣做時:

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

您只需創建一個局部變量,該局部變量僅在該文件的范圍內可見。

如果您想在導入app之后使用app.io從另一個文件訪問它,則需要:

  • io添加為應用程序的屬性:

     app.io = io; 

或簡單地將兩者結合起來:

    app.io = require('socket.io').listen(app);
  • 當然,導出應用程序本身

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