In this tutorial, we will learn how to obtain the names of all the files in a specific folder using Node.js. This can be achieved by utilizing the built-in fs module provided by Node.js.

To get started, you need to have the fs module available. Node.js comes with this module by default, so there is no need to install it separately.

Listing Files in a Folder

The following code snippet demonstrates how to list all the files and folders contained within a specified directory in the filesystem:

const fs = require('fs');

const directory = '/Users/flavio/folder';
const files = fs.readdirSync(directory);

for (const file of files) {
    console.log(file);
}

Here, we first import the fs module using require('fs'). Next, we define the path of the directory we want to list in the directory variable. The fs.readdirSync() method is then used to synchronously read the contents of the specified directory, returning an array of file names.

We iterate over the files array using a for...of loop and log each file name to the console using console.log(file).

Getting File Details

If you need to access additional information about a file, such as its size, permissions, or whether it is a directory, you can utilize the fs.lstatSync() method along with the path module. The code snippet below demonstrates how to achieve this within the existing for loop:

const path = require('path');

//...

//inside the `for` loop
const fileStat = fs.lstatSync(path.join(directory, file));

In this example, we import the path module using const path = require('path'). Then, inside the for loop, we use fs.lstatSync() to retrieve the file’s status object, which contains various details about the file. The path.join() method is used to concatenate the directory path and the file name, ensuring the correct path is provided to fs.lstatSync().

Within the fileStat object, you can access properties such as isFile() (returns true if the entry is a file), isDirectory() (returns true if the entry is a directory), size (the size of the file in bytes), and many more.

And that’s it! You now know how to retrieve the names of all files in a folder using Node.js. Feel free to experiment and enhance this code to suit your specific requirements.

Tags: Node.js, file management, filesystem, fs module, path module