简体   繁体   中英

timing issues in node.js

i'm having trouble understanding how to correctly handle assignments in node callbacks. I'm reading a config file and setting it's values in an express app using props to parse the .yaml. When i try and use what i've apparently set i can't app.get these values. (cfg_decoder is required from the props module). The console.log() works properly in the callback but how to I handle app.get outside of the callback or know when the values have been set?

app = express()

fs.readFile('./config.yaml', function (err,data) {
  if (err) {
    return console.log(err);
  }

  cfg = cfg_decoder(data);
  app.set('title', cfg['title'])
  app.set('port', cfg['port'])

  console.log(app.get('title'))

});

On a side note, is this a good way of setting configuration options?

You should be able to use the app.get() method within any scope as long as the express object has been instantiated.

You could have your fs.readFile() function return your settings values and then have app.set() be done outside of the scope of the read function.

function read(file){
    var content;
    fs.readFileSync(file, function (err, data) {
        if (err) return console.log(err);
        content = cfg_decoder(data);
    });
    return content;
}

var config = read('./config.yaml');
app.set('title', cfg['title'])
app.set('port', cfg['port'])

For my applications I use a config.js file or you could use a config.json file (which would be easier). In my .js file I just have an object array declaration and have it export out that object.

Config.js :

var config = {
    host: '127.0.0.1',
    port: '8000',
    title: 'Title',
    /* etc */
};
module.exports = config;

App.js :

var config = require('./config'),
    express = require('express'),
    app = express();

app.set('title', config.title);
app.listen(config.port, config.host);

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM