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;
If your data object is static then you can export it in index.js and import it at server.js
If data object is generated or fetched (asynchronous) then you have to create getter function that is called from server.js and returns data value. But be aware that data might then be undefined, so after getting the object please check.
Another solution for dynamic data would be to create function that gets data asynchronous and then calls your callback provided in server.js,
You can export router and data variable in your index.js:
module.exports.router = router;
module.exports.data = data;
And then in server.js import data and router like this:
var router = require('./routes/index.js').router;
var data = require('./routes/index.js').data;
app.use(router); //instead of app.use(require('./routes/index.js'));