DEV Community

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

Posted on

1 1

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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay