Thursday 20 April 2017

How do I prevent file writing errors in node.js?

Here is how I see a breakdown of two users trying to write on the same file at about 5ms apart even though such an event is pretty unlikely. 1. User 1 sends a post request with data 2. The data is received and fs.write is opened 3. User 2 sends a post request with data 4. The data is received and fs.write is opened

As I understand it, because of the asynchronous nature of node.js, while the instance is waiting for the asynchorous callback from fs.write, fs.write could be called again which could leading to an error because according to the docs "Note that it is unsafe to use fs.write multiple times on the same file without waiting for the callback."

I guess a synchronous version of fs.write could be used because then, due to the single threaded nature of node.js, user 2 would have to wait until everything for user 1 is finished. However, as I understand it, clusters could create the possibility of writing to the same file even if the write is synchronous. I am still a bit confused on child processes and how they would relate to this issue.



via Michael Brown

No comments:

Post a Comment