Sergio
Sergio

Reputation: 28845

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;
    });
});

Upvotes: 1

Views: 1169

Answers (1)

Brad
Brad

Reputation: 163593

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.

Upvotes: 1

Related Questions