Categories
JavaScript Answers

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

Spread the love

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 readdir and readFile methods.

For instance, we write

const fs = require('fs');

fs.readdir(dirname, (err, filenames) => {
  if (err) {
    onError(err);
    return;
  }
  filenames.forEach((filename) => {
    fs.readFile(dirname + filename, 'utf-8', (err, content) => {
      if (err) {
        onError(err);
        return;
      }
      onFileContent(filename, content);
    });
  });
});

to call fs.readdir to read the file paths from the dirname folder.

Then we get the filenames array from the callback parameter.

And then we call filenames.forEach with a callback that calls fs.readFile to read file with path dirname + filename.

And we get the content of the file from the content parameter in the readFile callback.

Conclusion

To read all files in a directory, store them in objects, and send the object with Node.js, we can use the readdir and readFile methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *