fs读取文件夹下的文件并生成json

2022-03-23  本文已影响0人  汀上

1.需求场景:需要做一个11*8的由本地图片构成的列表,设计发过来的图片物料是一个文件夹,结构如下

文件夹
   文件夹1
       img.jpg
   文件夹2
       img.jpg
       img.PNG

由于文件较多,自己拼写一个json比较麻烦,所以使用fs写了一段自动生成json的代码

const fs = require('fs');
const files = fs.readdirSync('./1/');   //把设计给的文件夹命名为1并放到当前目录下
var obj= [];
function fileList(files,path,father){
    files.forEach(function (item, index) {
        fs.stat(path+item, function(err, st) {
            if (err) {
                console.log(err);
            } else{
                if(st.isDirectory()){
                    fileList(fs.readdirSync(path+item+'/'),path+item+'/',item)
                }else{
                    obj.push({
                        path:'./about/'+father+'/'+item,   //这里是我本地文件需要放的位置
                        tittle:item.split(/.jpeg|.jpg|.png|.JPEG|.PNG|.JPG/)[0],
                        classify:father
                    })
                }
            }
        })
    })
}
fileList(files,'./1/');
//等待上面执行完,可以优化处理,这里简单粗暴地放个定时器,就可以直接打印在终端
setTimeout(d=>{
    console.log('==>',obj)},
1000)

最后的结构是

 [
    {
        "path": "./about/文件夹1/img.jpg",
        "title": "img",
        "classify": "文件夹1"
    },
    {
        "path": "./about/文件夹2/img.jpg",
        "title": "img",
        "classify": "文件夹2"
    },
    {
        "path": "./about/文件夹2/img.PNG",
        "title": "img",
        "classify": "文件夹2"
    },
]
上一篇下一篇

猜你喜欢

热点阅读