简体   繁体   中英

NodeJS request and error handling

I have a browsers.json file I want to update on each deploy.

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.

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