Synchronous Versus Asynchronous File System Calls

The fs module provided in Node.js makes almost all functionality available in two forms: asynchronous and synchronous. For example, it offers the asynchronous form write() and the synchronous form writeSync(). It is important to understand the difference when you are implementing code.

Synchronous file system calls block until a call completes and then control is released back to the thread. This has advantages but can also cause severe performance issues in Node.js if synchronous calls block the main event thread or too many of the background thread pool threads. Therefore, you should limit the use of synchronous file system calls when possible.

Asynchronous calls are placed on the event queue to be run later. This allows the calls to fit into the Node.js event model, but it can be a bit tricky when executing your code because the calling thread continues to run before the asynchronous call gets picked up by the event loop.

For the most part, the underlying functionality of both synchronous and asynchronous file system calls is exactly the same. Both synchronous and asynchronous file system calls accept the same parameters, with one exception: All asynchronous calls require an extra parameter at the end, a callback function to execute when the file system call completes.

The following list describes the important differences between synchronous and asynchronous file system calls in Node.js:

Image Asynchronous calls require a callback function as an extra parameter. The callback function is executed when the file system request completes and typically contains an error as its first parameter.

Image Asynchronous calls automatically handle exceptions and pass an error object as the first parameter if an exception occurs. To handle exceptions in synchronous calls, you must use try/catch blocks.

Image Synchronous calls run immediately, and execution does not return to the current thread until they complete. Asynchronous calls are placed on the event queue, and execution returns to the running thread code, but the actual call does not execute until it is picked up by the event loop.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.59.8