Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you export a variable from app.js into another route in Node js

i'm using socket.io in my node project and wanted to know how to possibly export the io variable

this is what i have done so far but i get this error: Object #<Object> has no method 'on'

in app.js:

        var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index')(io);
var users = require('./routes/user');

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(4000);

require('./routes/index')(io);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// app.use(favicon(__dirname + '/public/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

/// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err,
            title: 'error'
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {},
        title: 'error'
    });
});
/*
io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});
*/

module.exports = app;

in index.js

var io = require('../app');

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

the reason i want export the variable is so that i dont have to define io is index.js like i did in app.js which leads to me basically defining both server and app variable !

I just want to do all my socket.io stuff in the index.js route essentially (except from having to redefine the app, server and io variables in index.js ) !

Hope i have explained my self enough

Thank you !

like image 957
ipalibowhyte Avatar asked Nov 04 '14 17:11

ipalibowhyte


People also ask

Can I export variable JavaScript?

Use named exports to export multiple variables in JavaScript, e.g. export const A = 'a' and export const B = 'b' . The exported variables can be imported by using a named import as import {A, B} from './another-file.

How do I define a global variable in Express?

To set up a global variable, we need to create it on the global object. The global object is what gives us the scope of the entire project, rather than just the file (module) the variable was created in. In the code block below, we create a global variable called globalString and we give it a value.

How do you store local variables that can be access within the application in express js?

We can store local variables that can be accessed within the application by using app. locals.


2 Answers

Your dependencies are not set up correctly. You are executing index.js before io is initialized

var routes = require('./routes/index');
/* index.js starts being executed at this point
 * hence, io is undefined inside index.js
 */

Instead, why don't you try

app.js

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(4000);
module.exports = io;

var routes = require('./routes/index');
var users = require('./routes/user');

index.js

 var io = require('../app');

io.on('connection', function (socket) {
    socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
    console.log(data);
    });
});
like image 142
takinola Avatar answered Oct 21 '22 16:10

takinola


I think you need to use the sockets.

io.sockets.on('connection', ... ); 
like image 39
corn3lius Avatar answered Oct 21 '22 16:10

corn3lius