0

I have a code like this below. The code still use callback function and i want to change using promise. I hesistate how to change them. can you help how change it


const fs = require('fs')

fs.readdir('/', (err, result) => {
  if (err) {
    throw new Error(err.message)
  }
  console.log(result)
})

2 Answers2

0

fs.readdir('/') is already promise, you need to resolve it either with chaining like you did or with syntax sugare using async/await inside IIFE

(async () => {
   try{
        const result = await fs.readdir('/');
        console.log(result)
   }catch(err){
      console.log(err.message)
   }
})();
XMehdi01
  • 5,538
  • 2
  • 10
  • 34
  • 3
    This only works if you require the correct version of `fs`. -> `const fs = require('fs').promises` – Reyno Oct 27 '21 at 12:16
0

Provided that you import asycronous version of readdir() which is located in require('fs').promises you can read directories asyncronouly

const fs = require('fs').promises

const asyncReadDir = async(dirName) => {
    try {
         const dirData = await fs.readdir(dirName)
         console.log("Read successfully")
         // other code here
    } catch(error){
         // catch errors
         console.log(error)
    }
}

asyncReadDir("/downloads")
ABDULLOKH MUKHAMMADJONOV
  • 4,249
  • 3
  • 22
  • 40