0

I am trying to read and parse a local folder consisting of CSV files asynchronously. I have managed to figure out how to do it by hardcoding the files paths

const fsPromises = require('fs').promises
const parse = require('csv-parse/lib/sync')
const fs = require('fs')

async function readfile() {
  try {
    const fileData = await Promise.all([
      fsPromises.readFile(__dirname + '/testdata/a1.csv').then((file) =>
        parse(file, {
          columns: ['Date', 'Name', 'Value'],
          relax_column_count: true,
          fromLine: 2,
        })
      ),
      fsPromises.readFile(__dirname + '/testdata/b1.csv').then((file) =>
        parse(file, {
          columns: ['Date', 'Name', 'Value'],
          relax_column_count: true,
          fromLine: 2,
        })
      ),
    ])

    fileDataFlattened = fileData.flat()
    console.log(fileDataFlattened)
  } catch (err) {
    console.log(err)
  }
}

readfile()

I would now like to do it without having to hardcode the files. I figured out you could do this by creating an array of promises which with the functionality to read and parse the files from an array of file paths and using Promise.all to resolve the promises.

Unfortunately, I can't seem to figure out how to create this array of promises. Please help.

const fsPromises = require('fs').promises
const parse = require('csv-parse/lib/sync')
const fs = require('fs')

// reading an array of filenames from the path

const filePaths = fs.readdirSync(__dirname + '/testdata')

// creating an array of promises to read and parse the file as per the above code

[array of promises] = .......

async function readDirectory() {
    .....
    const fileData = await Promise.all([array of promises])
    .....
}
    
readDirectory()

1 Answer 1

3

Use .map() to call your file-reading function for each path.

Then use Promise.all() to wait for all of those promises to resolve.

If you have lots of files, you may want to consider e.g. p-limit to not read every single file concurrently.

const fsPromises = require("fs").promises;
const parse = require("csv-parse/lib/sync");
const fs = require("fs");

async function parseCSVP(path) {
  const file = await fsPromises.readFile(path);
  // TODO: use async CSV parser too?
  return parse(file, {
    columns: ["Date", "Name", "Value"],
    relax_column_count: true,
    fromLine: 2,
  });
}

async function stuff() {
  const filePaths = fs.readdirSync(__dirname + "/testdata");
  const fileReadPromises = filePaths.map(parseCSVP);
  const fileReadResults = await Promise.all(fileReadPromises);
  console.log(fileReadResults);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.