我有一个需要NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [[paths objectAtIndex:0]stringByAppendingString:@"csvfile"];
NSString *txtPath = [documentsDirectory stringByAppendingPathComponent:@"sample.csv"];
if ([fileManager fileExistsAtPath:txtPath] == NO) {
NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@".csv"];
[fileManager copyItemAtPath:resourcePath toPath:txtPath error:&error];
文件的应用程序才能绘制d3图表。但是我需要在data.json
- 事件:
onClick
上面是带有jquery-call的update-Button。在我的d3.select("#updatebutton").on("click", function(e) {
try{
$.get('https://localhost:4444/data', function(data) {
});
}
catch (e) {
alert('Error: ' + e);
}
});
文件中,我正在使用它:
app.js
});
通过https-Request接收app.get('/data', function(req, res, next) {
try{
getJSON();
}
catch(e) {
alert('Error');
}
- 功能数据,处理该数据并将其保存到getJSON()
:
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
没有被覆盖,但文件变得越来越大,意味着数据被添加到文件中而不是被覆盖。< / p>
我做错了什么?
感谢您的帮助。
答案 0 :(得分:2)
由于您使用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。原始函数完成后将触发回调函数。所以不要在回调函数中使用Try / Catch。
阅读:https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/