Three ways to work with File System in Node.js

nairihar
3 min readSep 26, 2022

--

It’s really common that you will need to work with the file system when you are working on a server-side project. The simplest things are reading and writing the files.

Over time Node.js introduced three different ways to work with the files.

Let’s explore them.

Callbacks

This is the simplest way to work with the file system asynchronously.

As a traditional callback. The first argument is defined only when there is an error. And the second one is when there is data to consume.

The callback type of operation doesn’t block the other processes. This kind of function work in the background. The function gets called but the actual work can take some time. You can have other processes working on another task in parallel. So don’t expect to have the work done until the callback isn’t called.

It’s hard to work with callbacks if you need to do sequential actions, where each process depends on the other. You may end up with callback hell.

Callback Hell

Sync functions

There is a different API which simplifies things for all the file system functions. Basically, all things work synchronously.

Here we get everything done on a single line.

But the disadvantage is that it blocks the main thread so your code will wait for that file system operation to be complete before it moves on to the next line of code.

Promises

And here is the latest API which has all the same functions in a promise-based way. In my humble opinion, this is the best option, mostly for all situations.

Similar to the callbacks, the processes work in the background.

With promises, we have a few more benefits.

First, we can use async/await which is syntactic sugar on top of the promises and provides a way to handle the asynchronous tasks in a synchronous manner.

Second, we can interact with promise’s built-in functions, which provides whole new opportunities that we can work with.

  • Promise.all (do things in parallel)
  • Promise.race (race the processes)
  • Promise.any (do things as soon as possible)
  • -and etc…

As a bonus, you can look into libraries like fs-extra that provide a bunch of functions to extend Node.js.

***

Thank you, feel free to ask any questions or tweet me @nairihar

Also follow my “JavaScript Universe” newsletter on Telegram: @javascript

--

--

nairihar
nairihar

Written by nairihar

Sharing valuable insights on the latest tools and trends in JavaScript. nairi.dev