1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
| const request = require("request"); const COS = require("cos-nodejs-sdk-v5"); const path = require("path"); const fs = require("fs");
const baseObj = { name: "", baseUrl: "example.com/galleries", cover: "", description: "", photos: [], };
const jsonPath = "xxx/galleries.json"; const Bucket = {}; const galleries = JSON.parse(fs.readFileSync(jsonPath));
function getBucketInfo() { return new Promise((res, rej) => { cos.getService((err, data) => { err ? rej(err) : res(data.Buckets[0]); }); }); }
async function getFileList() { try { let contents = await new Promise((res, rej) => { cos.getBucket( { Bucket: Bucket.Name, Region: Bucket.Location, Prefix: "galleries/", }, (err, data) => { err ? rej(err) : res(data.Contents); } ); }); return contents; } catch (e) { console.log(e); } }
async function init() { try { Object.assign(Bucket, await getBucketInfo()); refreshGalleries(); } catch (e) { console.log(e); } }
function isEXists(name) { for (let [index, item] of galleries.entries()) { console.log(item.name) console.log(index) return item.name === name ? index : false; } return false }
function buildGallery(name) { let model = fs.readFileSync("./burket/index.md", { encoding: "utf-8" }); model = model.replace("name", name); fs.mkdirSync(`./source/galleries/${name}`,{recursive:true}) fs.writeFileSync(`./source/galleries/${name}/index.md`, model,{ flag:'w+' }); }
async function refreshGalleries() { let contents = await getFileList(); let folders = new Map(); contents.forEach((item) => { let arr = item.Key.split("/"); if (arr.length === 3 && arr[2]) { let photos = folders.get(arr[1]); photos ? photos.unshift(arr[2]) : folders.set(arr[1], []); } }); for (let [name, photos] of folders.entries()) {、 let index = isEXists(name) if (index !== false) { galleries[index].photos = photos; continue } let gallery = Object.assign({},baseObj, { name, baseUrl: `${baseObj.baseUrl}/${name}/`, photos, cover: photos[0], }); galleries.push(gallery); buildGallery(name); } fs.writeFileSync(jsonPath, JSON.stringify(galleries)); }
init();
|