Last active
January 16, 2022 15:14
-
-
Save Leyka/1632a06c9feaec72ac7b841ee7e269b7 to your computer and use it in GitHub Desktop.
File to find images in node folder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require('path'); | |
const fs = require('fs'); | |
const _ = require('lodash'); | |
const uuid = require('uuid'); | |
const galleryName = 'gallery'; | |
const publicPath = path.join(__dirname, 'public'); | |
const galleryPath = path.join(publicPath, galleryName); | |
let gallery = {}; | |
function generate() { | |
if (!fs.existsSync(galleryPath)) return; | |
// Loop through folders (albums) | |
const albums = fs | |
.readdirSync(galleryPath, { withFileTypes: true }) | |
.filter((el) => el.isDirectory()) | |
.map((dir) => dir.name); | |
// Fetch pictures of each album | |
albums.forEach(createAlbum); | |
// Write gallery in JSON file | |
const jsonFile = path.join(publicPath, `${galleryName}.json`); | |
const galleryStringify = JSON.stringify(gallery); | |
fs.writeFileSync(jsonFile, galleryStringify); | |
} | |
function createAlbum(folder) { | |
const folderPath = path.join(galleryPath, folder); | |
const pictures = fetchPictures(folderPath, folder); | |
if (!pictures || pictures.length === 0) return; | |
gallery[folder] = { | |
name: _.capitalize(folder), | |
pictures, | |
}; | |
} | |
function fetchPictures(albumPath, albumName) { | |
return fs | |
.readdirSync(albumPath) | |
.filter(isPicture) | |
.map((pic) => toPicture(pic, albumPath, albumName)); | |
} | |
function isPicture(fileName) { | |
fileName = fileName.toLowerCase(); | |
return fileName.endsWith('.jpg') || fileName.endsWith('.jpeg') || fileName.endsWith('.png'); | |
} | |
function toPicture(fileName, albumPath, albumName) { | |
const picturePath = path.join(albumPath, fileName); | |
const pictureName = path.parse(picturePath).name; | |
// When using with React (create-react-app), we won't precise the public path | |
// see: https://create-react-app.dev/docs/using-the-public-folder/ | |
const picturePathReact = path.join(galleryName, albumName, fileName); | |
return { | |
id: uuid.v4(), | |
name: humanize(pictureName), | |
path: picturePathReact, | |
}; | |
} | |
function humanize(str) { | |
return str | |
.replace(/^[\s_]+|[\s_]+$/g, '') | |
.replace(/[_\s]+/g, ' ') | |
.replace(/^[a-z]/, function (m) { | |
return m.toUpperCase(); | |
}); | |
} | |
module.exports = generate; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment