简体   繁体   English

缓存node.js json服务器数据

[英]node.js json-server data are cached

I'm using the following json-server 我正在使用以下json服务器

var server = jsonServer.create()
var router = jsonServer.router('./books/db.json')
server.use(jsonServer.defaults())
server.use(router)
server.listen(3000)

I change db.json every 5 seconds 我每5秒更改一次db.json

setInterval(function() {
    var o = JSON.parse(fs.readFileSync('./books/db.json', 'utf8'));
    for (var i = 0; i < o.books.length; i++) {
        // do some changes
    }
    fs.writeFile("./books/db.json", JSON.stringify(o));
}, 5000);

the file is changing but when doing a request, it stills has the old data 该文件正在更改,但是在执行请求时,它仍然具有旧数据

json-server uses lowdb internally for serving static files . json-server内部使用lowdb提供静态文件 lowdb won't reload your file on change as it is not watching the file for changes. lowdb不会在更改时重新加载文件,因为它不监视文件中的更改。 The lowdb database is available at router.db , so you can use router.db.read('./books/db.json') to read your file again after changing it. lowdb数据库位于router.db ,因此可以在更改文件后使用router.db.read('./books/db.json')再次读取文件。 See the lowdb docs for the API. 有关API,请参见lowdb文档

Alternatively, read the section of the json-server docs pertaining to generating random data . 另外,请阅读json-server文档中与生成随机数据有关的部分。 This solution avoids continual disk access, but your data will be lost after the server exits. 此解决方案避免了持续的磁盘访问,但是服务器退出后,数据将丢失。 If this is not an issue, this would the the way I would go. 如果这不是问题,那将是我的选择。

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

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