1

i have an application which needs a data.json file in order to draw a d3-graph. However i need to update that file on an onClick-Event:

d3.select("#updatebutton").on("click", function(e) {
        try{
            $.get('https://localhost:4444/data', function(data) {
            });
        }
        catch (e) {
            alert('Error: ' + e);
        }
    });

Above is the update-Button with the jquery-call. In my app.js File I am using it like this:

app.get('/data', function(req, res, next) {
    try{
        getJSON();
}
catch(e) {
    alert('Error');
    }

});

The getJSON()-Function is received Data over an https-Request, processes that data and saves it to 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;
        });
    });
});
}

However if i click on my updateButton repeatedly after seconds, it seems that data.json is not overwritten but the file gets bigger and bigger, means that data is added to the file instead of overwritten.

What am I doing wrong?

Thanks for help.

1 Answer 1

2

Since you use app.get as your route, I guess you are using express.

In your routes definition:

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

});

In your browser js file:

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

I see you use try / catch around callback functions. The callback function fires after the original function completes. So don't use Try / Catch around callback function.

Read: https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/

Sign up to request clarification or add additional context in comments.

12 Comments

It seems to me @dnkss23 wants to fetch a file from somewhere else, and store it on the server. Not post the data from the browser at all. Why the data needs to be stored intermediately on the server, I don't know.
That can be done on the server alone, you don't need the browser for that. Best to use Request or something like that on the server.
yes @LinusGustavLarssonThiel is right! I want to load the data from somewhere else and save it on the server. However the saved file gets not overwritten but the content is added to the existing file. Why?
@blablabla But i want the user to be able to update the data manually by a button-click-event. So I do need the browser, right? I tried your solution, but it does not fix the 'Overwrite-Problem' and i get an additional error:'Can't set headers after they are sent.'
From your example, it makes no sense at all. My guess is that there is something happening in "// process data" in the example.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.