Wednesday, 12 April 2017

Node.js: Async fs.writeFile queue is creating race condition?

I am trying to use async with node.js to handle multiple incoming POST requests to edit a JSON file. No matter how I refactor it, it will always make one of the edits and not the other. I though that using async.queue would force the operations to handle sequentially? What am I doing wrong?

My code:

var editHandler = function(task, done) {

    var req = task.req;
    var res = task.res;

    fs.stat( "./app//public/json/" + "data.json", function(err, stat) {
        if(err == null) {
            console.log('File exists');
        } else if(err.code == 'ENOENT') {
            console.log("Error");
        } else {
        console.log('Some other error: ', err.code);
        }
    });
    console.log(req.params.id);
    console.log(req.body);

    fs.readFile( "./app//public/json/" + "data.json", 'utf8', function (err, data) {
       data = JSON.parse( data );
       data[req.params.id] = req.body.school;
       //console.log( data );
       fs.writeFile("./app//public/json/" + "data.json", JSON.stringify(data), function (err){
        if(err) {
            return console.log(err);
        }
       })
       res.redirect('/');
    });
};

//Make a queue for the services
var serviceQ = async.queue(editHandler, 20);

serviceQ.drain = function() {
    console.log('all services have been processed');
}

app.post('/edit_school/:id', function(req, res) {

   serviceQ.push({req: req, res: res }) 

})

Thanks in advance for any insights! I am really new to using node.js for anything other than npm/webpack.



via Jason B.

No comments:

Post a Comment