Published at
Updated at
Reading time
2min

This post is part of my Today I learned series in which I share all my learnings regarding web development.

That's a quick one. 🙈

When writing Node.js scripts and using the fs module I usually used the util.promisify method to promisify the methods that I needed.

Today I learned that fs since Node.js 11 provides the methods in a promises property. 🎉

// old way have using promise-based fs methods
const { readFile } = require("fs");
const { promisify } = require('util');
const promisifiedReadFile = promisify(readFile);

promisifiedReadFile(__filename, { encoding: "utf8" })
  .then(data => console.log(data));

// --------------------

// new way of using promise-based fs methods
// no util.promisify!!!
const { readFile } = require("fs").promises;
readFile(__filename, { encoding: "utf8" })
  .then(data => console.log(data));

Using the promises property you can now skip one step and there is no need to use promisify. That's excellent news to flatten some source code and go all in with async/await!

fs/promises is available since Node.js 14

Section titled `fs/promises` is available since Node.js 14

Update: Since Node.js v14 the fs modules provides two ways to use promises-based file-system methods. The promisified methods are available via require('fs').promises or require('fs/promises').

// Since Node.js v14: use promise-based fs methods
// no util.promisify!!!
const { readFile } = require("fs/promises");
readFile(__filename, { encoding: "utf8" })
  .then(data => console.log(data));

I'm very excited about the /promises path addition. The Node.js maintainers seemed to agree on this way to expose more promise-based methods in the future.

In Node.js v15 the Timers module also provides an experimental timers/promises package. That means you can do await setTimeout soon – Node.js is evolving! 🎉

If you want to read more Node.js tips and tricks head over to the Node.js section on my blog.

Related Topics

Related Articles