How to read all files in a directory, store them in objects, and send the object with Node.js?

Sometimes, we want to read all files in a directory, store them in objects, and send the object with Node.js.

In this article, we’ll look at how to read all files in a directory, store them in objects, and send the object with Node.js.

How to read all files in a directory, store them in objects, and send the object with Node.js?

To read all files in a directory, store them in objects, and send the object with Node.js, we can use the promise versions of the fs module methods.

For instance, we write

const fs = require('fs');
const util = require('util');

const readdir = util.promisify(fs.readdir);
const readFile = util.promisify(fs.readFile);

const readFiles = async dirname => {
  try {
    const filenames = await readdir(dirname);
    console.log({
      filenames
    });
    const filesPromise = filenames.map(filename => {
      return readFile(dirname + filename, 'utf-8');
    });
    const response = await Promise.all(filesPromise);
    return filenames.reduce((acc, filename, currentIndex) => {
      const content = response[currentIndex];
      return {
        ...acc,
        [filename]: content
      };
    }, {});
  } catch (error) {
    console.error(error);
  }
};

to define the readFiles function.

In it, we call readdir with the dirname folder path to get the file paths in the folder.

Then we call filenames.map to map each filename to a promise that resolves to the file content by calling readFile.

Then we call Promise.all with filesPromise to return a promise which resolves to an array of all the file contents.

And then we call filenames.reduce get the file content from response[currentIndex] and return an object with the filename as the property name and content as their values.

The fs methods are converted to functions that returns promises with

const readdir = util.promisify(fs.readdir);
const readFile = util.promisify(fs.readFile);

Conclusion

To read all files in a directory, store them in objects, and send the object with Node.js, we can use the promise versions of the fs module methods.