Node.js failed to traverse the folder asynchronously

I want to traverse all the png files under / images and cram their paths into an array

directory structure

clipboard.png



clipboard.png

this await is not valid.

Apr.20,2022

isn't there an asynchronous call inside foreach? resolve is definitely not allowed outside


since I know how to use await/async and promise, why use a bunch of callback? this is my own test. Available, you can take a look at

const fs = require('fs');
const path = require('path');
const { promisify } = require('util');

const readdir = promisify(fs.readdir);
const stat = promisify(fs.stat);

let imgPathArr = [];

async function loopFile(folder) {
  let files = await readdir(folder);

  for(let i=0; i<files.length; iPP) {
        let file = await stat(path.join(folder, files[i]));
        if(file.isFile()) {
            imgPathArr.push(path.join(folder, files[i]));
        }else{
            await loopFile(path.join(folder, files[i]));
        }
  }
}

(async () => {
  await loopFile(path.join(__dirname, 'files'));
  console.log(imgPathArr);
)();
Async exists in the

loop. It is recommended to use the for loop


this is not a code problem. It's your nodemon observation file that changes. You try to shut down nodemon first.

Menu