How to recursively scan all folders and files with nodejs on Windows

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

To recursively scan all folders and files in a directory using Node.js on Windows, you can use the built-in fs (file system) module along with recursion. The fs module allows you to interact with the file system, while recursion enables you to traverse through directories and subdirectories to scan all files.

Here's a Node.js script to recursively scan all folders and files in a directory:

javascript
const fs = require('fs');
const path = require('path');

function scanDirectory(directoryPath) {
// Read the contents of the directory
fs.readdir(directoryPath, (err, files) => {
if (err) {
console.error(`Error reading directory ${directoryPath}: ${err.message}`);
return;
}

// Loop through the files in the directory
files.forEach((file) => {
// Get the full path of the file/directory
const filePath = path.join(directoryPath, file);

// Check if it's a file or directory
fs.stat(filePath, (statErr, stats) => {
if (statErr) {
console.error(`Error getting stats for ${filePath}: ${statErr.message}`);
return;
}

if (stats.isFile()) {
// It's a file, do something with it
console.log(`File: ${filePath}`);
} else if (stats.isDirectory()) {
// It's a directory, recursively scan it
scanDirectory(filePath);
}
});
});
});
}

// Call the function with the root directory path
const rootDirectory = 'C:/path/to/root/directory';
scanDirectory(rootDirectory);

Replace 'C:/path/to/root/directory' with the actual path of the directory from which you want to start scanning. The script will traverse all directories and subdirectories, logging the names of the files encountered.

Keep in mind that the above code uses asynchronous functions of the fs module, which is more efficient for large directory structures. If you prefer synchronous operations, you can use fs.readdirSync and fs.statSync instead.

Make sure to handle any errors appropriately, as reading and scanning directories may throw exceptions for various reasons, such as insufficient permissions or invalid paths.