Answer the question
In order to leave comments, you need to log in
How to use map with an array filled asynchronously?
I use the readdir function to fill the array [path + file name] and I want to use map to read the contents of each file, but the array does not have time to fill, how can I fix this?
I need to use exactly readdir, so don't suggest synchronous readdirSync
For example:
const filePaths = /*здесь функция с readdir */;
return filePaths.map(path => readFile(path));
Answer the question
In order to leave comments, you need to log in
const fs = require('fs');
const path = require('path');
async function readDirFiles(dir) {
const filePaths = await fs.promises.readdir(dir, {withFileTypes: true});
return await Promise.all(
filePaths
.filter(e => e.isFile())
.map(async (e) => {
const p = path.join(dir, e.name)
return {
path: p,
content: await fs.promises.readFile(p, {encoding: 'utf8'})
};
})
);
}
readDirFiles('.')
.then(files => {
console.log(files);
})
.catch(err =>
console.error(err)
);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question