简体   繁体   English

node.js中的计时问题

[英]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. 我正在读取配置文件,并在快速应用程序中使用props解析.yaml来设置它的值。 When i try and use what i've apparently set i can't app.get these values. 当我尝试使用我显然设置的内容时,我无法app.get这些值。 (cfg_decoder is required from the props module). (在props模块中需要cfg_decoder)。 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? console.log()在回调中可以正常工作,但是如何在回调之外处理app.get或知道何时设置值?

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. 只要已实例化Express对象,就应该能够在任何范围内使用app.get()方法。

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. 您可以让fs.readFile()函数返回设置值,然后在read函数范围之外执行app.set()。

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). 对于我的应用程序,我使用config.js文件,也可以使用config.json文件(这会更容易)。 In my .js file I just have an object array declaration and have it export out that object. 在我的.js文件中,我只有一个对象数组声明,并将其导出到该对象。

Config.js : Config.js

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

App.js : 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. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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