Welcome folks today in this blog post we will be displaying all files
present inside a directory in command line. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.js
file and copy paste the following code
index.js
1 2 3 4 5 6 7 8 9 10 |
// Import the filesystem module const fs = require("fs"); let directory_name = ""; // Open the directory let openedDir = fs.opendirSync(directory_name); // Print the pathname of the directory console.log("\nPath of the directory:", openedDir.path); |
As you can see that guys in the above javascript code we are taking the root directory. And we need to display all the files present in the root directory. For this first of all we have required the fs
module which is built in module in node.js and after that we are using the opendirSync()
method to actually open the directory
or folder and in the argument we are passing the path of the directory. And then we are printing the pathname of the directory in console.
Displaying All Files in Directory
Now guys we will be showing all the files present inside the directory in the command line. First of all we will be using the readSync() method on the actual directory. This will return the array of files which are there. Now to loop through all the files and folders and display it we will be using the while
loop and we will check for the boolean property that this function returns either null or true. If the files are empty then it will return null and the loop will stop. The code is shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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; } |