Thursday 27 April 2017

How to pass variable from route to server.js

I'm having problem with sending current data to new socket connections. I have a server.js file with current code:

server.js:

// Importing and initializing npm/node plugins
var app = require('express')();
var server = require('http').createServer(app);

// Import config settings
var config = require('./config.js');

// Create socket server and allow connections from certain ip
var io = require('socket.io')(server);
io.set('origins', 'http://' + config.url + ':' + config.client_http_port);


app.use(require('./routes/index.js'));


// Create mongoDB connection
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://' + config.url + '/' + config.database_name);

// Inform new socket connections
io.on('connection', function (socket) {
    console.log('Client connected!');
    setTimeout(function () {
      // socket.emit('variable comes here');   <------------
    }, 3000);
});

// Open server in port
server.listen(config.server_port, function () {
    console.log('Server listening on port: ' + config.server_port);
});

module.exports = app;

In my index.js route I have a variable that I want to pass to server.js and from there to the new socket connections. How could I import the variable from route index.js to the server file server.js?

index.js:

// Importing and initializing npm/node plugins
var express = require('express');
var router = express.Router();

var data = {test:'data123'}; // <--------- this one

module.exports = router;



via Jack M.

No comments:

Post a Comment