Json不能正确保存使用node.js

我连接到websocket,每次我得到的消息,我把它的内容保存到一个JSON文件。如果我在同一秒得到两个或更多的消息它不妥妥保存它。如何防止?每次我得到的消息,我是使用:

fs.readFile(bought_path,'utf-8',(err,data) =>{ ... //do something 

阅读json文件,和

 fs.writeFile(bought_path, JSON.stringify(kupljeni_itemi) , 'utf-8'); 

保存编辑的json文件。

一种防范的方法是制作一个简单的locking机制:

 let isLocked = false; // declare it in an upper scope. if (!isLocked) { // check if it is not locked by other socket call. isLocked = true; // set the lock before writing the content fs.writeFile(file, json, (err) => { isLocked = false; // unlock when you get the response }) } 

你可以使用同步读/写function – readFileSyncwriteFileSync