使用node进行文件操作二:遍历指定目录下的所有文件,并打印路径

时间:2020-05-27 15:51:13   收藏:0   阅读:36

前言

本文主要任务是读取目录,准确的说是遍历指定目录下的所有文件,并打印路径

文件目录

技术分享图片

文件代码

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;
}

 

预期效果

技术分享图片

参考来源

代码仓库地址

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

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

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!