Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"io is not defined" #1418

Closed
TrangNguyen opened this issue Feb 13, 2014 · 17 comments
Closed

"io is not defined" #1418

TrangNguyen opened this issue Feb 13, 2014 · 17 comments

Comments

@TrangNguyen
Copy link

Hi,

I'm trying to integrate the mean stack (linnovate) with socket.io and I got this error " io is not defined". The issue is also referenced here linnovate/mean#272.

//server.js
var server = require('http').createServer(app);
var io = require('socket.io').listen(server, {
    'log level': 2
});
io.sockets.on('connection', function(socket) {
    console.log('Client Connected');
}); //<<<<<< 'socket' is defined but never used (linting error)
...
server.listen(port); 
//public/js/services/socket.js
angular.module('mean.socket').factory('socket', ['$rootScope',  function ($rootScope) {
    var socket = io.connect();
    return {
... // like Brian Ford did
    }
}]);
// app/views/includes/foot.html which feeds into the index.html
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="/js/services/socket.js"></script>
// public/js/app.js
angular.module('mean', ['ngCookies', 'ngResource', 'ngRoute', 'ui.bootstrap', 'ui.route', 'mean.system', 'mean.articles', 'mean.socket']);
angular.module('mean.socket', []);

This is the error

Linting server.js ...ERROR
[L56:C44] W098: 'socket' is defined but never used.
io.sockets.on('connection', function(socket) {
Linting public/js/services/socket.js ...ERROR
[L4:C18] W117: 'io' is not defined.
  var socket = io.connect();

I don't know what I am missing. I have no error consoled to the browser, socket.io.js is loaded properly, socket.io starts server side but nothing works. I have tried to give specific url to io.connect(), load socket.io.js from cdn but it doesn't change. 'io is not defined', what does it mean, any help, any hint greatly appreciated.
Trang

@Anachron
Copy link

What if you try this?

//server.js
var server = require('http').createServer(app);
var io = require('socket.io').listen(server, {
    'log level': 2
});
io.socket.on('connection', function(socket) {
    console.log('Client Connected');
});
...
server.listen(port); 

@TrangNguyen
Copy link
Author

Thanx for your reply.
I have the same error message of "io not defined". When I checked network ( Chrome dev tool) no socket connection, no socket.id is found.
on Terminal

   info  - socket.io started
Express listening at port 3000
GET / 200 81ms
   debug - served static content /socket.io.js

and no more.
Any idea of how I should debug it further? Thanx.

@Anachron
Copy link

May I ask what port is defined as?
Because I can see it being used but nowhere the declaration.

@TrangNguyen
Copy link
Author

the port is defined in server.js as:

var port = process.env.PORT || config.port; //in this case 3000

@Anachron
Copy link

Do you mind dumping some values like io, port, server and app and put them into pastebin or github gist?

@TrangNguyen
Copy link
Author

I have it up on github https://github.com/TrangNguyen/meansocket.
Thanks, t.

@Anachron
Copy link

After looking at https://github.com/TrangNguyen/meansocket/blob/master/server.js I'm asking myself:
Why are you having this:

...
var server = http.createServer(app);
...
server.listen(port);
//app.listen(port);
....

When you have this

var app = express();

This doesn't work?

'use strict';

/**
 * Module dependencies.
 */
var express = require('express'),
    fs = require('fs'),
    passport = require('passport'),
    logger = require('mean-logger'),
    http = require('http');

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */

// Load configurations
// Set the node enviornment variable if not set before
process.env.NODE_ENV = process.env.NODE_ENV || 'development';

// Initializing system variables 
var config = require('./config/config'),
    mongoose = require('mongoose');

// Bootstrap db connection
var db = mongoose.connect(config.db);

// Bootstrap models
var models_path = __dirname + '/app/models';
var walk = function(path) {
    fs.readdirSync(path).forEach(function(file) {
        var newPath = path + '/' + file;
        var stat = fs.statSync(newPath);
        if (stat.isFile()) {
            if (/(.*)\.(js$|coffee$)/.test(file)) {
                require(newPath);
            }
        } else if (stat.isDirectory()) {
            walk(newPath);
        }
    });
};
walk(models_path);

//seed our users
require('./config/user-seed.js')();

// Bootstrap passport config
require('./config/passport')(passport);

var app = express();

// Express settings
require('./config/express')(app, passport, db);

// Bootstrap routes
var routes_path = __dirname + '/app/routes';
var walk = function(path) {
    fs.readdirSync(path).forEach(function(file) {
        var newPath = path + '/' + file;
        var stat = fs.statSync(newPath);
        if (stat.isFile()) {
            if (/(.*)\.(js$|coffee$)/.test(file)) {
                require(newPath)(app, passport);
            }
        // We skip the app/routes/middlewares directory as it is meant to be
        // used and shared by routes as further middlewares and is not a 
        // route by itself
        } else if (stat.isDirectory() && file !== 'middlewares') {
            walk(newPath);
        }
    });
};
walk(routes_path);


// Start the app by listening on <port>
var port = process.env.PORT || config.port;

var socketIO = require('socket.io').listen(app, {
  'log level': 3
});
socketIO.sockets.on('connection', function (socket) {
  console.log('connect to something');
  socket.on('disconnect', function () {
    console.log('bye bye');
  });
});

app.listen(port);
console.log('Express app started on port ' + port);

// Initializing logger
logger.init(app, passport, mongoose);

// Expose app
exports = module.exports = app;

@TrangNguyen
Copy link
Author

I thought express 3 need to have http.createServer before socket can be hooked to and "app = express()" is not equivalent, i think. I tried your suggestion and socket isn't hooked onto client.

Failed to load resource: the server responded with a status of 404 (Not Found) 
GET /socket.io/socket.io.js 404 59ms

@Anachron
Copy link

I have to admit I am not very used to socket.io, I'm using a third party library to automatically load and hook it into my coffeescript-app. (Mimosa)

This is a direct copy and paste from the socket.io site:

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

app.listen(80);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

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

The difference from your app is the order in which the app is listened.

@TrangNguyen
Copy link
Author

I'm not fit either, as you can see. But thanks for your time.

@TrangNguyen
Copy link
Author

I figured it out. Thanks.

@Anachron
Copy link

Anachron commented Mar 3, 2014

Thanks for your feedback, what was the problem, may I ask?

@TrangNguyen
Copy link
Author

I don't really know actually. I mean the error message stays the same but the app works. I eventually switched to use json web token like this app and added socketio, socketio-jwt on to it. I also use raphael.sketchpad script on my app to draw svg and jslint also complaints about the raphael object although it works.

@jspeev
Copy link

jspeev commented Dec 11, 2014

You can also tell JSHint that io is a global variable. it recognizes this comment notation and won't bother warning you that io isn't being defined in your service (which it doesn't need to be since it's global) just put this before your module declaration at the top of your factory service

/* globals io */
angular.module(...

@lysudo
Copy link

lysudo commented Feb 15, 2022

while having your src codes in another path than the root dir then you have to specify the full path so :

instead of <script type="text/javascript" src="/socket.io/socket.io.js"></script>

try : <script type="text/javascript" src="http://[yourDomain]/socket.io/socket.io.js"></script>

@Anachron
Copy link

You're a bot, no?

Why do you reply to a 7 year old thread with no meaningful reply whatsoever?

@lysudo
Copy link

lysudo commented Mar 17, 2022

we can't confirm neither deny ..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants
@Anachron @TrangNguyen @jspeev @lysudo and others