How to List all Files in a Directory using Node
Table of Contents
As a back-end runtime, you can use Node to perform file system operations on the server that it is running on.
One of the most common operations is listing all of the files from a directory.
In this post, we'll learn how to use Node to list all of the files in a directory with a given path.
How to list all of the files in a directory
To read files from the directory, we'll be using the fs
module, the module used for file system operations.
In this module is the method readdir
that we can use to list all of the files in a directory.
Simply pass it the path of the directory you want to list the files from, and it will return an array of all of the files in that directory.
Let's say this is the path to the directory that you want to check:
JAVASCRIPTconst path = "/path/to/directory";
JAVASCRIPTimport { promises as fs } from 'fs';
const path = "/path/to/directory";
const files = await fs.readdir(path);
files.forEach(file => console.log(file));
Keep in mind that this operation will be done asynchronously, which is why we use the await
keyword.
If you need to do this synchronously, you can use the fs
module directly with the readdirSync
method.
JAVASCRIPTimport fs from 'fs';
const path = "/path/to/directory";
const files = fs.readdirSync(path);
files.forEach(file => console.log(file));
Either way, you'll get an array of all of the files in the directory, including their file extensions.
Conclusion
In this post, we learned how to use Node to list all of the files in a directory using a path you provide.
You can either do this asynchronously or synchronously using the fs
module.
Thanks for reading this post!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Electron
- How to Serve Static Files with Nginx and Docker
- How to build a Discord bot using TypeScript
- How to deploy an Express app using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue