0

Since the server configuration is stored in an XML file before assigning the port to app for listening I have to read the XML file, convert the XML string output to JSON for readability. I also using node clusters to make node performing better. Below is the code snippet.

//getschema.js
module.exports = function(callback) {
    var filepath='serverconfig.xml';
    var fs = require('fs');
    var xml2js = require('xml2js');
    fs.readFile(filepath, 'utf8', function (err, xmlStr) {
        if (err) throw (err);
        xml2js.parseString(xmlStr, {}, function(err, json){
             callback(json.serverconfig);
        });
    });    
 };

//server.js
var serverdetails   = require('./getschema');
var port;
serverdetails(function(config) {
        port      = config.port;//getting port values as 4000
});

const cluster       = require('cluster');

if (cluster.isMaster) {
  for (let i = 0; i < numCPUs; i++) {
     cluster.fork();
  }
} else {
        console.log(port); //getting undefined
        const server = app.listen(port, () => {
             console.log(`Worker ${process.pid} started`);
        });
        const io = require('socket.io')(server);
}

The issue what I am facing now is as shown in the above code, I am not able to assign the port got from config file as the server port. The value is available in the serverdetails(function(config) {}. Since the node code execution is asynchronous that value is not available in const server = app.listen(port, () => { .

Can anyone suggest a solution for fixing this issue? Thanks.

Soojoo
  • 2,146
  • 1
  • 30
  • 56

1 Answers1

0

Just call server.listen asynchronously :

if (cluster.isMaster) {
     (...) 
} else {
    serverdetails(function(config) {
        var port      = config.port;//getting port values as 4000
        console.log(port); //getting the correct value 
        const server = app.listen(port, () => {
            console.log(`Worker ${process.pid} started`);
        });
       const io = require('socket.io')(server);
   }) ;
}
Lorenz Meyer
  • 19,166
  • 22
  • 75
  • 121