Dr. McKay
Dr. McKay

Reputation: 2977

Is it safe to use write() multiple times on the same file without regard for concurrency as long as each write is to a different region of the file?

According to the docs for fs:

Note that it is unsafe to use fs.write multiple times on the same file without waiting for the callback. For this scenario, fs.createWriteStream is strongly recommended.

I am downloading a file in chunks (4 chunks downloading at a time concurrently). I know the full size of the file beforehand (I use truncate after opening the file to allocate the space upfront) and also the size and ultimate location in the file (byte offset from beginning of file) of each chunk. Once a chunk is finished downloading, I call fs.write to put that chunk of data into the file at its proper place. Each call to fs.write includes the position where the data should be written. I am not using the internal pointer at all. No two chunks will overlap.

I assume that the docs indicate that calling fs.write multiple times without waiting for the callback is unsafe because you can't know where the internal pointer is. Since I'm not using that, is there any problem with my doing this?

Upvotes: 0

Views: 1260

Answers (1)

minzchickenflavor
minzchickenflavor

Reputation: 516

No its not safe. Simpy because you don't know if the first call to write has been successful when you execute the second call.

Imagine if the second call was successful but the first and third call wasn't and the fifth and sixth were successful as well. And the chaos is perfect.

Plus NodeJS has a different execution stack than other interpreters have. You have no guarantee when specific code parts will be executed or in which order

Upvotes: 0

Related Questions