Node.js gives unpredictable ajax response on the first time of startup

妖精的绣舞 提交于 2019-12-01 12:08:43

The problem is that you're calling app.get("json"); before its value has been set by the fs.readfile callback in app.init (which occurs sometime after the first call to app.init(); returns).

You should probably change your code to only call app.init once, and don't listen for requests until its work completes.

app.init = function(callback){
    fs.readFile('./sample.json', 'utf8', function(error, data) {
        if (error) {
            throw(error);
        } else {
            app.set("json", data);
            callback();
        }
    });
};

...

app.init(function() {
    app.listen(3000);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!