JavaScript Development Space

Get All Files and Folders in Node.js Directories

3 November 20244 min read
Exploring Directories in Node.js: Retrieve All Files and Folders

In this tutorial, we’ll look at how to read all .mdx files in a directory structure like this:

Loading code editor...

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:

Loading code editor...

This function lists all directories within a specified path by filtering out non-directory items.

2. Flattening Arrays:

Loading code editor...

The flatten function merges nested arrays into a single-level array, simplifying handling directory structures.

Loading code editor...

Recursively collects all directories and subdirectories under a given path.

4. Retrieving MDX Files:

Loading code editor...

This function searches for .mdx files in a specified directory.

5. Retrieve MDX Files from Multiple Folders:

Loading code editor...

This function accepts an array of folder paths and retrieves .mdx files from each.

6. Reading MDX File Content and Metadata:

Loading code editor...

Here, gray-matter is used to parse front matter (metadata) from MDX files.

7. Compiling MDX Data:

Loading code editor...

8. Specific Data Retrieval for Blog

Loading code editor...

These functions streamline the retrieval of data for specific types of content.

9. Formatting Dates:

Loading code editor...

This function formats dates for blog posts, optionally including relative dates.

Full code

Loading code editor...

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.

JavaScript Development Space

JSDev Space – Your go-to hub for JavaScript development. Explore expert guides, best practices, and the latest trends in web development, React, Node.js, and more. Stay ahead with cutting-edge tutorials, tools, and insights for modern JS developers. 🚀

Join our growing community of developers! Follow us on social media for updates, coding tips, and exclusive content. Stay connected and level up your JavaScript skills with us! 🔥

© 2025 JavaScript Development Space - Master JS and NodeJS. All rights reserved.