1

I'm using the following json-server

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

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

1 Answer 1

4

json-server uses lowdb internally for serving static files. lowdb won't reload your file on change as it is not watching the file for changes. 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. See the lowdb docs for the API.

Alternatively, read the section of the json-server docs pertaining to generating random data. 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.