简体   繁体   中英

critical section in nodejs - writing data from frontend to json file

I have following question that have I to synchronize requests when writing data to a file from multiple users in the same time. In java there is a synchronized keyword but I don't understand how it looks in nodejs.

app.post("/register",function(req,res){

      fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
      var users=JSON.parse(data);
      users["users"].push(req.body);
      var check=false;
      fs.writeFile(__dirname + "/" + "users.json", JSON.stringify(users),'utf8', function (err) {
         if(err){
            res.send(JSON.stringify("error"));
            check=true;
         }
      })
      if(!check){
         res.send(JSON.stringify("Created")); 
      }
           
   })
})

You should use writeFileSync instead of writeFile.

It returns nothing, so if the process went to the next line, this mean the file was written successfully!!

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