Get All Files and Folders in Node.js Directories
3 November 20244 min read
In this tutorial, we’ll look at how to read all .mdx
files in a directory structure like this:
Managing markdown files, especially in .mdx format, can be essential for content-driven applications. This guide shows how to retrieve and process .mdx files in a nested directory structure using Node.js, fs, and gray-matter.
Check out this collection of code snippets for handling various folder and file operations efficiently.
1. Retrieve Directories:
This function lists all directories within a specified path by filtering out non-directory items.
2. Flattening Arrays:
The flatten
function merges nested arrays into a single-level array, simplifying handling directory structures.
3. Recursive Directory Search:
Recursively collects all directories and subdirectories under a given path.
4. Retrieving MDX Files:
This function searches for .mdx
files in a specified directory.
5. Retrieve MDX Files from Multiple Folders:
This function accepts an array of folder paths and retrieves .mdx
files from each.
6. Reading MDX File Content and Metadata:
Here, gray-matter
is used to parse front matter (metadata) from MDX files.
7. Compiling MDX Data:
8. Specific Data Retrieval for Blog
These functions streamline the retrieval of data for specific types of content.
9. Formatting Dates:
This function formats dates for blog posts, optionally including relative dates.
Full code
Conclusion
This setup allows you to organize and process .mdx
files in various directories, ideal for a blog or CMS system. Using fs
and gray-matter
, you can dynamically read and parse metadata and content, building a powerful, file-driven content management layer in Node.js.