9
9
9karamba2019-01-12 15:33:50
JavaScript
9karamba, 2019-01-12 15:33:50

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

2 answer(s)
A
Aves, 2019-01-13
@9karamba

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)
  );

K
Kirill Kudryavtsev, 2019-01-12
@Deissh

Use async/await if the result is a promise or a callback.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question