How it works…

The util module is standard with Node, and all you have to do to use it is the following:

const util = require("util");

The util.promisify() method is actually another example of a Higher Order Function, as we saw in the Producing functions from functions section of Chapter 2, Using JavaScript Modern Features.

Using util.promisify(), we can make fs.readFile() return a promise, which we'll process with the .then() and .catch() methods:

// ...continued

function showFileLength2(fileName: string): void {
fs.readFile = util.promisify(fs.readFile);

fs
.readFile(fileName, "utf8")
.then((text: string) => {
console.log(`2. Reading with promises: ${text.length} bytes`);
})
.catch((err: mixed) => {
throw err;
});
}
showFileLength2(FILE_TO_READ);

// continues...
You could have also written const { promisify } = require("util"), and then it would have been fs.readFile = promisify(fs.readFile)

This also allows us the usage of async and await; I'll be using an arrow async function, just for variety:

// ...continued

const showFileLength3 = async (fileName: string) => {
fs.readFile = util.promisify(fs.readFile);

try {
const text: string = await fs.readFile(fileName, "utf8");
console.log(`3. Reading with async/await: ${text.length} bytes`);
} catch (err) {
throw err;
}
};
showFileLength3(FILE_TO_READ);