DEV Community

Cover image for Sync/Async using the fs module in Node JS
Nishant Kumar Jha
Nishant Kumar Jha

Posted on

Sync/Async using the fs module in Node JS

On the journey of learning backend development with Node, I will be sharing my learnings each day.

1. Using fs module Synchronously:
Synchronous fs module

Output:

Sync result

2. Using fs module Asynchronously:
Asynchronous fs module

Output:

Async result

Conclusion:

  • Synchronous is the vanilla JavaScript way of executing code.

  • When the fs module is implemented using sync, the code execution takes place line-by-line and does not move to the next line until the current is executed.

  • Thus, the console logs written in the sync code are executed in the same sequence as they are written.

  • Whereas, when fs is implemented using async, we can notice the line starting next task is printed before done with this task, this explains the async behaviour of JS while using the fs module here.

  • The code uses a callback (oldest and non preferred method to implement asynchronous behaviour in JavaScript) function having err, result as the parameters.

Detailed explanation: When Node is parsing the code, as soon as it comes to the function call of readFile() which is an async function, it encounters a callback (or callback hell in this case) which rather than halting the code, lets it execute continuously, while waiting for the response from the readFile() function. Thus, the synchronous console.logs, which are outside of readFile() are executed first, letting the asynchronous code finish in parallel.

Top comments (0)