【发布时间】:2016-03-23 16:43:01
【问题描述】:
我有一个应用程序需要data.json 文件才能绘制 d3-graph。但是我需要在onClick-Event 上更新该文件:
d3.select("#updatebutton").on("click", function(e) {
try{
$.get('https://localhost:4444/data', function(data) {
});
}
catch (e) {
alert('Error: ' + e);
}
});
上面是带有 jquery 调用的更新按钮。在我的app.js 文件中,我是这样使用它的:
app.get('/data', function(req, res, next) {
try{
getJSON();
}
catch(e) {
alert('Error');
}
});
getJSON()-Function 通过 https-Request 接收数据,处理该数据并将其保存到 data.json:
function getJSON() {
var req = https.get(options, function(response) {
// handle the response
var res_data = '';
response.on('data', function(chunk) {
res_data += chunk;
});
response.on('end', function() {
//process data
// save to file
fs.writeFile(filePath, JSON.stringify(finalJson), function(err) {
if (err)
throw err;
});
});
});
}
但是,如果我在几秒钟后反复单击我的updateButton,似乎data.json 没有被覆盖,但文件越来越大,这意味着数据被添加到文件中而不是被覆盖。
我做错了什么?
感谢您的帮助。
【问题讨论】:
标签: javascript json node.js fs writefile