//操作文件 /* 1、fs.stat 獲取文件狀態 2、fs.readdir 讀取文件夾數據 3、fs.access 判斷文件夾是否存在 4、path.join 拼路徑 */ //操作文件 const fs = require('fs'); //操作路徑 const path = require('path'); //1.接受命令行命令 //3.判斷路徑是否存在 //2.修正路徑 let inputPath = process.argv[2];//[2]是輸入的路徑名 if(!inputPath) {//判斷有沒有輸入內容 throw '請輸入文件名!'; } //轉換路徑格式為絕對路徑 inputPath = path.resolve(inputPath); //輸入的路徑存在就執行遞歸 try{ //擴展:'.F_OK'==='檢查目錄中是否存在文件' //'.R_OK'==='檢查文件是否可讀',詳細見nodejs文檔 //也可以這樣寫 :判斷是否存在,以及是否可讀 //fs.accessSync(inputPath,fs.constants.F_OK|fs.constants.R_OK); //這里的 fs.constants.F_OK 是默認值,不用寫 fs.accessSync(inputPath); testReadFiles(inputPath); }catch(err){ console.log(err); } function testReadFiles(filePath){ let state = fs.statSync(filePath); if(state.isFile()){ //是文件 console.log(filePath) }else if (state.isDirectory()){ //是文件夾 //先讀取 let files = fs.readdirSync(filePath); files.forEach(file=>{ console.log(path.join(filePath,file)+',file') testReadFiles(path.join(filePath,file)); }); } }