loudking loudking - 1 month ago 5
Javascript Question

node.js/socket.io/express execution order

I am building a node.js application and would like to print some logging messages with version number. The version number should first be read from a Java properties file thus I am using a third-party library. The library provides a parse() function but documentation indicated that:

path - Boolean
By default parse() reads a String. If you want to read a file, set this option to true. If this option is used, the callback is mandatory. It gets 2 parameters, a possible error and the object with all the properties.


Now the problem is Node.js is asynchronous so there is no guarrentee that the version number is ready before printing. Please help.

var file_log='../log/log.txt';
var file_property='../backend/config.txt';

var log4js = require('log4js');
log4js.loadAppender('file');
log4js.addAppender(log4js.appenders.file(file_log), 'recon-frontend');
var logger = log4js.getLogger('recon-frontend');
logger.setLevel('info');

var arg = process.argv.slice(2);
if(arg.length) {
arg = parseInt(arg);
}
else {
arg = 2334;
}

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

http.listen(arg, function(){
var properties = require("properties");
var version;
properties.parse(file_property, { path: true }, function (error, obj){
if(error) {
return console.error(error);
}
console.log(obj);
console.log(obj.version);
version = obj.version;
});
logger.info("Recon frontend v"+version+" listening to port "+arg);
});


One possibility is of course to place the logging sentence inside parse callback function but it is confusing because that piece of information should only be ready if binding succeeds. Is there any other solution please? Thanks.

Answer

I finally figured out myself - using a module called 'properties-reader'