Javascript的Node.js完全覆盖文件
我有一个应用程序需要一个data.json
文件,以绘制一个D3图。 不过,我需要在onClick
-Event上更新该文件:
d3.select("#updatebutton").on("click", function(e) { try{ $.get('https://localhost:4444/data', function(data) { }); } catch (e) { alert('Error: ' + e); } });
以上是带有jquery调用的update-Button。 在我的app.js
文件中,我使用它是这样的:
app.get('/data', function(req, res, next) { try{ getJSON(); } catch(e) { alert('Error'); }
});
getJSON()
函数通过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
不会被覆盖,但文件变得越来越大,意味着数据被添加到文件而不是覆盖。
我究竟做错了什么?
感谢帮助。
由于您使用app.get作为您的路线,我猜你正在使用快递。
在你的路线定义中:
var getData = (function() { var callbacks = []; function executeCallbacks(err, data) { for (var i = 0; i < callbacks.length; i++) { callbacks[i](err, data); } callbacks = []; } return function(cb) { callbacks.push(cb); if( callbacks.length === 1 ) { var req = https.get(options, function(response) { // handle the response var res_data = ''; response.on('data', function(chunk) { res_data += chunk; }); response.once('end', function() { // process data here // save to file fs.writeFile(filePath, JSON.stringify(finalJson), function(err) { if (err) { // call error handler return executeCallbacks(err); } executeCallbacks(null, body); }); }); response.once('error', function() { return executeCallbacks(err); }); } req.end(); } }; })(); app.get('/data', function(req, res, next) { getData(function(err, data) { if(err) { return next(err); } return data; }); });
在您的浏览器js文件中:
d3.select("#updatebutton").on("click", function(e) { $.get( 'https://localhost:4444/data', function(data) { alert( "success" ); var json = JSON.parse(data); }) .fail(function() { alert( "error" ); }); });
我看到你使用try / catch周围的callback函数。 callback函数在原函数完成后触发。 所以不要使用Try / Catch围绕callback函数。
阅读: https : //strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/