oriaj
oriaj

Reputation: 798

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?

My code

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

});

the error that I get in this case is TypeError: Cannot read property 'sockets' of undefined

Blockquote

Upvotes: 1

Views: 3102

Answers (2)

jcaron
jcaron

Reputation: 17710

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:

  • add io as a property of your app:

    app.io = io;
    

or simply combine both:

    app.io = require('socket.io').listen(app);
  • of course, export the app itself

Upvotes: 4

madox2
madox2

Reputation: 51881

from the socket.io docs this should work:

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

Upvotes: 2

Related Questions