how to read file extension in a folder in node js
How to Read File Extensions in a Folder in Node.js
To read file extensions in a folder in Node.js, you can use the fs
(file system) module to interact with the file system and the path
module to extract the file extension from the file name. Here are the steps to accomplish this:
- Import the required modules:
- Use the
require
function to import thefs
module and assign it to a variable, such asfs
. Use the
require
function to import thepath
module and assign it to a variable, such aspath
.Read the contents of the folder:
- Use the
fs.readdir
function to read the contents of the folder. - Pass the folder path as the first argument to
readdir
. - Provide a callback function as the second argument to handle the result.
- In the callback function, check for any errors. If an error occurs, handle it appropriately.
If there are no errors, the result will be an array of file names.
Extract the file extension from each file name:
- Use the
path.extname
function to extract the file extension from each file name. - Pass each file name as an argument to
extname
. Store the file extensions in an array or process them as needed.
Handle the file extensions:
- You can perform various operations with the file extensions, such as filtering specific extensions, counting the occurrences of each extension, or performing any other desired logic.
Here's an example code snippet that demonstrates these steps:
const fs = require('fs');
const path = require('path');
const folderPath = '/path/to/folder';
fs.readdir(folderPath, (err, files) => {
if (err) {
console.error('Error reading folder:', err);
return;
}
const fileExtensions = files.map((file) => path.extname(file));
console.log('File extensions:', fileExtensions);
});
In this example, replace /path/to/folder
with the actual path to the folder you want to read. The readdir
function reads the contents of the folder, and the map
function extracts the file extensions using extname
. Finally, the file extensions are logged to the console.
Please note that this example assumes that the folder exists and that you have the necessary permissions to read its contents.