Mateen Kiani
Published on Sun Sep 24 2023·5 min read
When working with Node.js, it's common to need to read the contents of a directory, which may include both files and directories. In this article, we'll explore different methods to accomplish this task, and we'll also discuss the benefits of each approach.
In this method, we'll read all files and folders in a directory without using the “path” package. We'll rely solely on the built-in “fs” (file system) module.
const fs = require('fs');const directoryPath = '/path/to/your/directory';// Use fs.readdirSync to read the contents of the directory synchronouslyconst fileList = fs.readdirSync(directoryPath);console.log('Files and folders in the directory:', fileList);
Simplicity: This method is straightforward and does not require additional dependencies. It's a quick way to list the contents of a directory.
Synchronous: fs.readdirSync is a synchronous operation, which means it will block the Node.js event loop until the directory reading is complete. This can be beneficial in some scenarios when you want to ensure that the directory reading is finished before proceeding with other tasks.
In this method, we'll read all files and folders in a directory using the fs.readdir method, which is asynchronous.
const fs = require('fs');const directoryPath = '/path/to/your/directory';// Use fs.readdir to read the contents of the directory asynchronouslyfs.readdir(directoryPath, (err, files) => {if (err) {console.error('Error reading directory:', err);return;}console.log('Files and folders in the directory:', files);});
Non-blocking: This method is non-blocking, which means it won't pause the Node.js event loop while reading the directory. This is advantageous for applications that need to remain responsive.
Error Handling: It provides error handling through the callback function, making it suitable for scenarios where error handling is crucial.
Now, let's explore how to read the contents of a file from the list of files we obtained using one of the previous methods. We'll use fs.readFileSync for this purpose.
const fs = require('fs');const directoryPath = '/path/to/your/directory';// Assuming you have a fileList obtained from one of the previous methodsfileList.forEach((file) => {const filePath = `${directoryPath}/${file}`;try {const fileContent = fs.readFileSync(filePath, 'utf-8');console.log(`Contents of ${file}:`, fileContent);} catch (err) {console.error(`Error reading ${file}:`, err);}});
Synchronous Reading: fs.readFileSync reads file contents synchronously, which means it will block the event loop while reading the file. Use this method when you want to ensure that the file contents are available immediately.
Error Handling: It provides error handling through try-catch, making it suitable for scenarios where you need precise control over errors.
In this method, we'll specifically read and list only the files in a directory, excluding subdirectories.
Asynchronous Approach (Using fs.readdir):
const fs = require('fs');const path = require('path');const directoryPath = '/path/to/your/directory';// Use fs.readdir to read the contents of the directory asynchronouslyfs.readdir(directoryPath, (err, items) => {if (err) {console.error('Error reading directory:', err);return;}// Use async forEach to filter and log only filesitems.forEach((item) => {const itemPath = path.join(directoryPath, item);fs.stat(itemPath, (statErr, stats) => {if (statErr) {console.error(`Error reading ${item}:`, statErr);return;}if (stats.isFile()) {console.log('File:', item);}});});});
Non-blocking: This method is non-blocking, which is suitable for applications that need to remain responsive while reading files in the directory.
Granular Control: It allows for granular control over each file's properties (e.g., checking if it's a file or a directory) through fs.stat.
Synchronous Approach (Using fs.readdirSync):
const fs = require('fs');const path = require('path');const directoryPath = '/path/to/folder';// Use fs.readdirSync to read the contents of the directory synchronouslyconst filesAndFolders = fs.readdirSync(directoryPath);// Use filter function with path and fs package to filter only filesconst files = filesAndFolders.filter((item) => {const itemPath = path.join(directoryPath, item);const stats = fs.statSync(itemPath);return stats.isFile()})console.log("Files found in folder: ", files)
Simplicity: This method is straightforward and does not require nested callbacks or promises. It's a quick way to list only the files in a directory.
Synchronous Reading: It reads file properties and lists files synchronously, which may be beneficial in cases where you need to ensure that file listing is complete before continuing with other tasks.
In this comprehensive article, we've covered multiple methods for reading files and folders in a directory using Node.js. Each method offers its advantages, ranging from simplicity and blocking behavior to non-blocking asynchronous operations and granular control over file properties. By understanding these methods, you can efficiently work with directories and files in Node.js, making your file management tasks more manageable and reliable.