Published at
Updated at
Reading time
This post is part of my Today I learned series in which I share all my web development learnings.

That's a quick one. ๐Ÿ™ˆ

When writing Node.js scripts that use the fs module, I usually used the util.promisify method to promisify the file-system methods. Promises-based methods allow using async/await and that makes code easier to grasp and read.

Today I learned that since Node.js 11 the fs module provides "promisified" 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 the step to transform callbacks into promises 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

Update: Since Node.js 14 the fs module provides two ways to use the promises-based file-system methods. The promises 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 because the Node.js maintainers seem to agree on this way to expose more promise-based methods of existing modules 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 and that means less util.promisify and more coding! ๐ŸŽ‰

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

Was this TIL post helpful?
Yes? Cool! You might want to check out Web Weekly for more quick learnings. The last edition went out 8 days ago.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles