使用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

原文地址:https://www.cnblogs.com/xingguozhiming/p/12973332.html