我有一个可以获取天气信息的应用程序,然后将其显示到页面上。下面是我的一段代码。
app.post ('/weather',function(req,res){
let city = req.body.city;
$('#text').text(city);
fs.writeFileSync(__dirname + '/index.html', $.html());
getWeatherData(city);
res.sendFile(__dirname + '/index.html');
});
我知道Node.js具有事件驱动的体系结构,能够异步I / O,但是我该怎么做res.sendFile(__dirname + '/index.html');
这个动作是最近完成的呢?因为现在我获得了天气信息,所以将其写在index.html中,但显示了index.html的旧版本。
您可以将res.sendFile
放在fs.writeFile
的回调中,如下所示:
fs.writeFile(__dirname + ‘/index.html’, html, () => {
getWeatherData(city)
res.sendFile(__dirname + ‘/index.html’);
});
而且似乎您正在为每个用户编写不同的文件。只是一个建议,但我建议您考虑使用pug来提高效率。