Can Multiple fs.write to append to the same file guarantee the order of execution?

后端 未结 2 892
深忆病人
深忆病人 2021-01-04 20:20

Assume we have such a program:

// imagine the string1 to string1000 are very long strings, which will take a while to be written to file system
var arr = [\"         


        
2条回答
  •  独厮守ぢ
    2021-01-04 20:49

    You can synchronize the access to the file using the read/write locking for node, please see the following example an you could read the documentation

    var ReadWriteLock = require('rwlock');
    
    var lock = new ReadWriteLock();
    
    lock.writeLock(function (release) {
      fs.appendFile(fileName, addToFile, function(err, data) {
        if(err) 
          console.log("write error"); //logging error message
        else    
          console.log("write ok");
    
        release(); // unlock
       });    
    });
    

提交回复
热议问题