简体   繁体   English

NodeJS请求和错误处理

[英]NodeJS request and error handling

I have a browsers.json file I want to update on each deploy. 我有一个browsers.json文件,希望在每次部署时进行更新。

In case the request to update the file fails I would like to keep the original file unchanged. 万一更新文件的请求失败,我想保持原始文件不变。

Is this a good way to do it, or is there a "better practise" way? 这是一个好方法吗,还是有“更好的实践”方法?

var http = require('http');
var fs = require('fs');
var url = 'http://saucelabs.com/rest/v1/info/browsers/webdriver';

if (fs.existsSync('browsers.json')){ 
    var browsers = JSON.parse(fs.readFileSync('browsers.json'));
}

http.get(url, function (res) {
    var data = '';

    res.on('data', function (chunk) {
        data += chunk;
    });

    res.on('end', function () {
        var obj = JSON.parse(data);
        fs.writeFile('browsers.json', data, function (err) {
            if (err) throw err;
        });
    })

}).on("error", function () {
    fs.writeFile('browsers.json', browsers, function (err) {
        if (err) throw err;
    });
});

I would say that on error, you shouldn't be writing anything. 我会说,如果出错,您不应该写任何东西。 I would also say that it is generally best just to pipe the response directly to a writable stream on the file, so that you aren't buffering the whole thing in memory. 我还要说通常最好是将响应直接传递到文件上的可写流,这样就不会在内存中缓冲整个内容。 (Although, that might not matter much if your file is small.) (尽管,如果文件很小,那可能没什么大不了的。)

Finally, don't forget to re-parse and load the data once you have it. 最后,一旦拥有数据,别忘了重新解析和加载数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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