【发布时间】:2018-07-19 12:35:26
【问题描述】:
我正在使用节点模块 jsonfile 读取 json 文件并使用 express 模块和 res.json() 对其进行路由
据我了解,我不能使用异步读取,因为 json 的操作只能在回调中处理,因此实际上无法返回数据并使用 res.json() 提供数据
app.get('/api/announcements', function(req, res) {
res.json(utils.getAnnouncements())
})
getAnnouncements: function() {
data = jsonfile.readFile('announcements.json', function(err, obj) {
//return obj
})
//return data
}
是我想要的,但实际上这会返回 undefined 或 promise,具体取决于实现。
同步读取文件会阻塞整个服务器的执行还是仅仅阻塞app.get('/api/announcements')的事件循环
另外,最正确的方法是什么?
【问题讨论】:
标签: javascript json node.js fs