Home > Software design >  Using await in node.js
Using await in node.js

Time:06-12

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

CodePudding user response:

Because you are using callback method which doesn't waits to finish.

So solution use 'fs/promises' with await.

 const fsp = require('fs/promises')

//...

 const files =  await fsp.readdir(testFolder)

CodePudding user response:

for (const file of files) {
  filesToMove.push(file);
}

I think forEach does not work with files. I hope this will be helpful for you. Thanks.

CodePudding user response:

You using callback in readFile function. You need to use the async version for readdir.

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

let filesToMove = [];

async function readFiles() {
  const testFolder = "./files_to_move/";
   
  const files = await readdir(testFolder)
  files.forEach((file) => {
     filesToMove.push(file);
     console.log("done");
  });
}

async function printFiles() {
  await readFiles();

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