简体   繁体   中英

Node.js only reloads a json file on server restart although that should happen dynamically

I have a Post-form in my ejs-template that passes one object via Ajax/post without the page being reloaded. The handler in my app.js then saves the data into a data.json. All of this is working perfectly.

My only concern is that node seems to be requiring the json file only once, I have already tried using setInterval() which made no difference at all. The desired functionality is that the server reloads the data.json after every other submit of my form. Furthermore I have an iframe where the loaded data is displayed. This should happen on the fly therefore without any refresh of the page.

For your above comment socket has nothing to do with it.

To answer your question , you can keep that JSON in memory , creating that object as a global object accessible by every part of code (files).

code example ->

app.js -

global_json = require('../path/myJSON'); //please note that I am not using var here to make it global
//Rest of the code

file1.js -

module.exports = fun(req, res) {
    global_json.something = req.body.something;
//global_json accessible in every file
}

Alternative

If this is not the use case, then you can read and write file in every request (from post), although file reads/writes are slow but wont be the bottle neck in case of node.js server

function formpost(req, res) {
var data = req.body;
fs.writeFile('filename.json', JSON.stringify(data), cb);
}

//And same with reads

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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