Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using async/await with util.promisify(fs.readFile)?

Tags:

node.js

I'm trying to learn async/await and your feedback would help a lot.

I'm simply using fs.readFile() as a specific example of functions that has not been modernized with Promises and async/await.

(I'm aware of fs.readFileSync() but I want to learn the concepts.)

Is the pattern below an ok pattern? Are there any issues with it?

const fs = require('fs');
const util = require('util');

//promisify converts fs.readFile to a Promised version
const readFilePr = util.promisify(fs.readFile); //returns a Promise which can then be used in async await

async function getFileAsync(filename) {
    try {
        const contents = await readFilePr(filename, 'utf-8'); //put the resolved results of readFilePr into contents
        console.log('✔️ ', filename, 'is successfully read: ', contents);
    }
    catch (err){ //if readFilePr returns errors, we catch it here
        console.error('⛔ We could not read', filename)
        console.error('⛔ This is the error: ', err); 
    }
}

getFileAsync('abc.txt');
like image 703
Phu Ngo Avatar asked Sep 15 '25 09:09

Phu Ngo


1 Answers

import from fs/promises instead, like this:

const { readFile } = require('fs/promises')

This version returns the promise you are wanting to use and then you don't need to wrap readFile in a promise manually.

like image 108
shallow.alchemy Avatar answered Sep 17 '25 03:09

shallow.alchemy