【问题标题】:Does sync file reading block all javascript execution or just the event loop its reading in?同步文件读取是否会阻止所有 javascript 执行或仅阻止其读取的事件循环?
【发布时间】: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
}

是我想要的,但实际上这会返回 undefinedpromise,具体取决于实现。

同步读取文件会阻塞整个服务器的执行还是仅仅阻塞app.get('/api/announcements')的事件循环

另外,最正确的方法是什么?

【问题讨论】:

    标签: javascript json node.js fs


    【解决方案1】:

    整个 Node 进程都有一个事件循环,因此同步读取会阻塞所有内容。 (集群承受能力...)

    你想做这样的事情:

    app.get('/api/announcements', function(req, res) {
       //define anonymous function that will be used when getAnnouncements is done.
       utils.getAnnouncements(function(err,fileData){
         // handle if(err)
         res.json(fileData)
       })
    })
    
    getAnnouncements: function(callback) {
      //read file async, using callback function to handle results
      jsonfile.readFile('announcements.json', function(err, fileData) {
         callback(err, fileData)
      })
      //or just `jsonfile.readFile('announcements.json',callback)`
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-21
      • 1970-01-01
      • 2010-12-17
      • 1970-01-01
      相关资源
      最近更新 更多