需求:給定一個目錄,讀取該目錄下面的所有文件,包括該目錄下面文件夾里面的子文件,子子文件......
const fs = require('fs');
const path = require('path');
// 指定要遍歷的目錄
const directoryPath = 'D:\\';
//調用函數入口處
readDir(directoryPath);
//實現一個遞歸調用的函數
function readDir(directoryPath) {
? ? // 讀取目錄
? ? fs.readdir(directoryPath, (err, files) => {
? ? ? ?// console.log('directoryPath:------------', directoryPath);
? ? ? ? if (err) {
? ? ? ? ? ? return console.log('Unable to scan directory: ' + err);
? ? ? ? }
? ? ? ? files.forEach(file => {
? ? ? ? ? ? // 構造完整的文件路徑
? ? ? ? ? ? const fullPath = path.join(directoryPath, file);
? ? ? ? ? ? // 讀取文件狀態以判斷是文件還是目錄
? ? ? ? ? ? fs.stat(fullPath, (err, stats) => {
? ? ? ? ? ? ? ? if (err) {
? ? ? ? ? ? ? ? ? ? console.log('Error stating file:', err);
? ? ? ? ? ? ? ? ? ? return;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? if (stats.isDirectory()) {
? ? ? ? ? ? ? ? ? ? console.log(fullPath + ' is a directory');
? ? ? ? ? ? ? ? ? ? // 如果是目錄,可以選擇遞歸調用或者根據需要處理
? ? ? ? ? ? ? ? ? ? readDir(fullPath);
? ? ? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? ? ? console.log(fullPath + ' is a file');
? ? ? ? ? ? ? ? }
? ? ? ? ? ? });
? ? ? ? });
? ? });
}