Read/Write a file with Node.js 10+

Hugo Larrousse
2 min readSep 24, 2019

--

Introduction

This article shows how to write/read a file using nodejs + async/await and without any external package. We are going to use the amazing fs, the module already included in node.js 👌

The old way: Callbacks

First of all, let’s remember how we write and read a file using the traditional and most common asynchronous way.

Reading and writing a file using callback works well but it’s not the most elegant and simple way. Moreover, if you want to write several files you will unfortunately have the “callback hell” problem.

The new way: Async/Await

Nowadays, async/await has become the trand when we talk about asynchronous function but before 2019 there was no way to use fs (without any other module) and async/await. Things has changed!…

Please say hello to fs Promises API !

Basically and according the fs Promises documentation:

The fs.promises API provides an alternative set of asynchronous file system methods that return Promise objects rather than using callbacks

An exemple? Yes, sir, right away!

  • Read a file
  • Write a file

Voilà! You call the fs promises APi (line 1) and then you can use it just like any async function.
As you notice I used try/catch to grab errors.
That’s it, easy right?

Of course this new api provides many other methods, I let you check the documentation.

Be Careful !

3 things:

  • This new feature is only available for Node 10 and above.
  • Before Node 11, you will still get a warning that this feature is experimental, but don’t worry it works perfectly fine.
  • Since version 11.14.0, the feature is no longer experimental ! 😎

Thanks for reading! ❤

It’s my first publication on Medium so don’t hesitate to share any feedback. The next article will probably be less “technical” and about something very different like being a web developer in Brazil for exemple ;)

Sign up to discover human stories that deepen your understanding of the world.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Hugo Larrousse
Hugo Larrousse

Written by Hugo Larrousse

French guy | Born to travel | Web Developer at @heptaward | Javascript Lover | NodeJs fan | AngularJs nostalgic (yes the 1.X) | Budding designer

Responses (2)

Write a response