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 – readFileSync
和writeFileSync
- Node.js不closures由fs.createReadStream()创build的文件
- fs.createReadStream – 限制一次传输的数据量
- 哪种方式更好地把文件从服务器的亚马逊S3?
- nodejsasynchronous读取不断增长的文件
- Node.js:console.log消息不显示,如果方法抛出exception…为什么?
- Node.js中的fs.ReadStream和fs.createReadStream是否有区别?
- 从node.js(fs模块)中的文件stream中删除最后一个字符
- fs.writeFileSync在Windows上给ENOENT错误
- 节点fs错误:EPERM:操作不允许,打开