How does NodeJS handle IO file aync file?

Working with NodeJS for some time, I was wondering how node handles file operations inside.

Given the following pseudo code:

initialize http server on connection: modify_some_file: on success: print "it worked" 

Consider two users A and B who are trying to access a page almost simultaneously. Suppose further that A is the first that connects, then the following happens:

  • A connects
  • NodeJS initializes the file operation and tells the operating system to be notified after it is completed.

And here is what interests me: let them say that the file operation is not completed yet, and B connects, what does node do? How and when does it access the file when it is still in the process of "changing"?

I hope my question is somewhat clear;) We are waiting for your answers!

+4
source share
1 answer

AFAIK, Node doesn't care.

At least on Unix, it is legal to have multiple authors in a single file. Sometimes this is not a problem (let's say your file consists of records of a fixed size, where record No. 1 is written to record X and record No. 2 is written to record Y with X! == Y), and sometimes it is (the same example: when both writers want to record X).

In Node, the problems are mitigated because the I / O operations are "in turn", but I think that there is still the potential of two authors receiving each other. It is up to the programmer to make sure that this does not happen.

With Node, you can use *Sync() versions for fs operations (but they will block your application during the operation), use the add mode (which is only atomic to certain record sizes, I think, and it depends on your requirements, if adding really useful), use some form of locking, or use something like a queue in which write operations will be queued, and there is one queue consumer for processing records.

+3
source

Source: https://habr.com/ru/post/1484023/


All Articles