1.需求場景:需要做一個(gè)11*8的由本地圖片構(gòu)成的列表,設(shè)計(jì)發(fā)過來的圖片物料是一個(gè)文件夾,結(jié)構(gòu)如下
文件夾
文件夾1
img.jpg
文件夾2
img.jpg
img.PNG
由于文件較多,自己拼寫一個(gè)json比較麻煩,所以使用fs寫了一段自動(dòng)生成json的代碼
const fs = require('fs');
const files = fs.readdirSync('./1/'); //把設(shè)計(jì)給的文件夾命名為1并放到當(dāng)前目錄下
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/');
//等待上面執(zhí)行完,可以優(yōu)化處理,這里簡單粗暴地放個(gè)定時(shí)器,就可以直接打印在終端
setTimeout(d=>{
console.log('==>',obj)},
1000)
最后的結(jié)構(gòu)是
[
{
"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"
},
]