natli
natli

Reputation: 3822

Are multiple async file appends on the same file safe?

Looking at the pseudo-code below, is it possible for the writes to the file to become mangled?

for(var i=0;i<5;i++)
  fs.appendFile("myfile.txt", "myline"+i+'\n', somecallback)

fs is found here

Possibility I'd expect:

myline3
myline4
myline1
myline2
myline0

But would this be possible?

mylimyline4
ne3
myline1
myline2
myline0

In which case the second append would have occurred in the middle of the first. Because if this can happen I'll have to queue the writes manually.

Upvotes: 5

Views: 213

Answers (1)

grabantot
grabantot

Reputation: 2149

I wrote a programm to test that and was unable to make it mix different appends.

var fs = require('fs')

var filename = __dirname + '/file.bin'
var bytes_per_buff = parseInt(process.argv[2]) || 4096
var num_buffs = parseInt(process.argv[3]) || 256
var buffs = []

for (var i=0; i<num_buffs; i++) {
    buffs[i] = new Buffer(bytes_per_buff)
    for (var j=0; j<bytes_per_buff; j++) {
        buffs[i][j] = i
    }
}

fs.writeFile(filename, '', ()=>console.log('file created'))
for (var i=0; i<num_buffs; i++) {
    (function(buff_num) { //closure to log buff_num
        fs.appendFile(filename, buffs[buff_num], ()=>console.log(buff_num))
    }(i))
}

Upvotes: 1

Related Questions