mikewhit
mikewhit

Reputation: 121

Is `fs.readFile` equivalent to `setTimeout(fs.readFileSync)`?

General remarks are that asynchronous file reads are quicker. What I want to know is if there is an underlying implementation detail that makes fs.readFile fundamentally different from fs.readFileSync OR if placing the "synchronous" call inside of an asynchronous context makes it indistinguishable from the asynchronous file read.

Thanks!

Upvotes: 0

Views: 547

Answers (1)

jfriend00
jfriend00

Reputation: 707318

Is fs.readFile equivalent to setTimeout(fs.readFileSync)?

No, the two are not the same at all. fs.readFileSync() blocks the event loop and ALL other execution for the entire duration of the readFile operation. Putting it in a setTimeout() just changes when it runs, it doesn't change the fact that the event loop is still blocked for the entire duration of reading the file (when it runs).

Said another way, setTimeout() just influences when it runs (to some time in the future), it doesn't move its execution outside of the main event loop when it does actually run.

fs.readFile(), on the other hand, does all the file reading outside the javascript thread (using native threads in libuv) and is non-blocking. You call fs.readFile() and it returns immediately allowing your code to go about doing other things. Other events can be processed and other code can run while it is reading the file. The event loop is not blocked while the file is being read. Then, when the entire file has been read, an event will be posted in the event loop and the main Javascript thread will be notified of the completion of the file reading.

What I want to know is if there is an underlying implementation detail that makes fs.readFile fundamentally different from fs.readFileSync

Yes, there is a fundamental difference. fs.readFile() is asynchronous and does its file reading in a different thread from the Javascript thread. It is non-blocking. While it's doing the file reading in the other thread, other Javascript can run.

fs.readFileSync() is blocking. That means that during the whole time that the file is being read, the event loop is blocked and NO other Javascript can run.

Upvotes: 2

Related Questions