Click here to Skip to main content
16,021,169 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a function that reads files in a directory and pushes their name into an array. But every time I try to print the array, it's empty because the code does not wait for the function to finish, even though I used await that suppose to make the code wait for the function.

here is the code:

let filesToMove = [];

async function readFiles() {
  const testFolder = "./files_to_move/";

  fs.readdir(testFolder, (err, files) => {
    files.forEach((file) => {
        filesToMove.push(file);
      console.log("done");
    });
  });
}

async function printFiles() {
  files = await readFiles();

  console.log(filesToMove.length);
  filesToMove.forEach((item) => {
      console.log(item);
  });
}


Thank you in advance

What I have tried:

I don't really know what to try. I new at this. I would appreciate any material that can help me understand.
Posted
Updated 12-Jun-22 22:24pm

1 solution

Your readFiles function does not return a Promise. The printFiles function has nothing to await.

If you're using Node.js v10 or later, you can use fsPromises.readdir[^] instead:
JavaScript
import { readdir } from 'node:fs/promises';

async function readFiles() {
  const testFolder = "./files_to_move/";
  return await readdir(testFolder);
}

async function printFiles() {
  const filesToMove = await readFiles();
  console.log(filesToMove.length);
  filesToMove.forEach(item => console.log(item));
}
Otherwise, you'd need to convert the call to a promise and return that:
JavaScript
function readFiles() { /* NB: Not "async" */
  const testFolder = "./files_to_move/";
  return new Promise((resolve, reject) => {
    fs.readdir(testFolder, (err, files) => {
      if (err) {
        reject(err);
      } else {
        resolve(files);
      }
    });
  });
}

async function printFiles() {
  const filesToMove = await readFiles();
  console.log(filesToMove.length);
  filesToMove.forEach(item => console.log(item));
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900