When working with Node.js, it's common to need to fetch a list of files with a specific file extension from a directory. This task can be easily accomplished using Node.js's built-in `fs` module. In this article, we'll walk you through the step-by-step process of how you can retrieve a list of files with a specific file extension in Node.js.
First things first, ensure that you have Node.js installed on your system. You can check this by running `node --version` in your terminal.
To begin, open your preferred code editor and create a new JavaScript file. Let's name it `fileSearch.js`. In this file, we will write the Node.js script to find files with a specific file extension.
const fs = require('fs');
const path = require('path');
const directoryPath = './'; // Specify the directory where you want to search for files
const extensionToSearch = '.txt'; // Specify the file extension you are looking for
fs.readdir(directoryPath, (err, files) => {
if (err) {
console.error('Error reading directory:', err);
return;
}
const filteredFiles = files.filter(file => path.extname(file) === extensionToSearch);
console.log('Files with extension', extensionToSearch + ':', filteredFiles);
});
In this script, we first require the `fs` and `path` modules provided by Node.js. We specify the `directoryPath` where we want to search for files and the `extensionToSearch` that we are looking for, in this case, `.txt` files.
Next, we use the `fs.readdir` function to read the contents of the specified directory. The callback function processes the array of `files` retrieved from the directory. We then filter these files based on the extension using the `path.extname` method and compare it with the `extensionToSearch`. Any file matching the specified extension is added to the `filteredFiles` array.
Finally, we log the list of files with the specific file extension to the console.
Save the file, open your terminal, navigate to the directory where `fileSearch.js` is located, and run the script using the command `node fileSearch.js`.
You should see an output displaying the list of files with the specified file extension in the directory you provided.
And that's it! You now have a handy script in Node.js that can fetch a list of files with a specific file extension. Feel free to customize the `directoryPath` and `extensionToSearch` variables to suit your specific requirements.
Happy coding!