How to display all files in a directory using Node.js ?
Last Updated :
21 May, 2020
The files present in a directory can be displayed using two approaches in Node.js that are discussed below:
Method 1: Using fs.readdirSync() method: The
fs.readdirSync()
is a method that is available in the file system module of Node.js. It is used for reading the contents of a directory. It returns an array of file paths, buffers, or fs.Dirent objects.
The returned array of files can be looped through using the forEach() loop and the file names can be displayed from it. This allows one to display all the filenames present in the directory.
The asynchronous variation of the method
fs.readdir()
can also be used in place of this function that returns a callback with the files instead of the files themselves.
Example:
javascript
// Import the filesystem module
const fs = require("fs");
let directory_name = "example_dir";
// Function to get current filenames
// in directory
let filenames = fs.readdirSync(directory_name);
console.log("\nFilenames in directory:");
filenames.forEach((file) => {
console.log("File:", file);
});
Output:
Filenames in directory:
File: file_a.txt
File: file_b.txt
File: file_c.txt
Method 2: Using the fs.opendirSync() method: The
fs.opendirSync()
method is available in the file system module of Node.js. It can be used to read the contents of a directory. It returns an
fs.Dir
object that represents the given directory.
The
fs.Dir
object can be used to access the files in that directory using the
readSync()
method. This method returns an
fs.Dirent
object that contains the representation of the directory entry. This object has a
name
property that can be used to get the file name that this
fs.Dirent
object refers to. This name can be accessed and displayed to this user. The
readSync()
method will automatically read the next directory entry and return null when no more entries exist. This can be used to continuously loop through the entries and get all the file names using a while loop.
The asynchronous variation of the method
fs.opendir()
can also be used in place of this function that returns a callback with the
fs.Dir
object instead of the object itself.
Example:
javascript
// Import the filesystem module
const fs = require("fs");
let directory_name = "example_dir";
// Open the directory
let openedDir = fs.opendirSync(directory_name);
// Print the pathname of the directory
console.log("\nPath of the directory:", openedDir.path);
// Get the files present in the directory
console.log("Files Present in directory:");
let filesLeft = true;
while (filesLeft) {
// Read a file as fs.Dirent object
let fileDirent = openedDir.readSync();
// If readSync() does not return null
// print its filename
if (fileDirent != null)
console.log("Name:", fileDirent.name);
// If the readSync() returns null
// stop the loop
else filesLeft = false;
}
Output:
Path of the directory: example_dir
Files Present in directory:
Name: file_a.txt
Name: file_b.txt
Name: file_c.tx
Similar Reads
How to Create a Directory using Node.js ? In this article, we will create a directory using NodeJS. NodeJS has Filesystem(fs) core module, which enables interacting with the file system, has Node.js fs.mkdir() method or Node.js fs.mkdirSync() method method, to create new directory /parent directory. Prerequisites:Node File SystemThe approac
3 min read
How to Download a File Using Node.js? Downloading files from the internet is a common task in many Node.js applications, whether it's fetching images, videos, documents, or any other type of file. In this article, we'll explore various methods for downloading files using Node.js, ranging from built-in modules to external libraries.Using
3 min read
How to Copy a File in Node.js? Node.js, with its robust file system (fs) module, offers several methods to copy files. Whether you're building a command-line tool, a web server, or a desktop application, understanding how to copy files is essential. This article will explore various ways to copy a file in Node.js, catering to bot
2 min read
How to Display Images using Handlebars in Node.js ? In this article, we will discuss how to display images using handlebars in Node.js. You may refer to this article for setting up handlebars View Engine in Node.jsApproachTo display images using Handlebars in Node.js, pass the image URLs to the template from your server. In the Handlebars template, u
3 min read
How to convert a file to zip file and download it using Node.js ? The Zip files are a common way of storing compressed files and folders. In this article, I'll demonstrate how to convert the file to zip format by using the adm-zip module (NPM PACKAGE).Uses of ADM-ZIPcompress the original file and change them to zip format.update/delete the existing files(.zip form
3 min read
How to Get Information About a File using Node.js ? Node.js is an open-source and cross-platform runtime environment built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. You need to recollect that NodeJS isnât a framework, and itâs not a programming language. In this article, we will discuss how to get informatio
3 min read
How to read and write files in Node JS ? NodeJS provides built-in modules for reading and writing files, allowing developers to interact with the file system asynchronously. These modules, namely fs (File System), offer various methods for performing file operations such as reading from files, writing to files, and manipulating file metada
2 min read
How to return an array of lines from a file in node.js ? In this article, we will return an array of lines from a specified file using node.js. The fs module is used to deal with the file system in node.js and to read file data we use fs.readFileSync( ) or fs.readFile( ) methods. Here we will use the readFileSync method to read the file, and we use the st
2 min read
How to check the given path is file or directory in node.js ? Sometimes there is a need to check whether the given path is a file or directory so that different operations can be performed based on the result. For instance, to log the information of the directory and file separately. In Node.js, file handling is handled by the fs module. You can read more abo
4 min read