使用node進行文件操作(二):遍歷指定目錄下的所有文件,並打印路徑


前言

本文主要任務是讀取目錄,准確的說是遍歷指定目錄下的所有文件,並打印路徑

文件目錄

image.png

文件代碼

const fs=require('fs');
const path=require('path');
/**
 * 遍歷指定目錄下的所有文件
 * @param {*} dir 
 */
const getAllFile=function(dir){
    let res=[]
    function traverse(dir){
        fs.readdirSync(dir).forEach((file)=>{
            const pathname=path.join(dir,file)
            if(fs.statSync(pathname).isDirectory()){
                traverse(pathname)
            }else{
                res.push(pathname)
            }
        })
    }
    traverse(dir)
    return res;
}

 

預期效果

image.png

參考來源

代碼倉庫地址

https://github.com/XingGuoZM/ming-scripts


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM