Sort gallery images by date

This commit is contained in:
Cohee
2024-08-15 00:40:08 +03:00
parent e2a2e3869e
commit a08b3ec7fc
2 changed files with 21 additions and 4 deletions

View File

@ -82,7 +82,7 @@ router.post('/list/:folder', (request, response) => {
} }
try { try {
const images = getImages(directoryPath); const images = getImages(directoryPath, 'date');
return response.send(images); return response.send(images);
} catch (error) { } catch (error) {
console.error(error); console.error(error);

View File

@ -382,14 +382,31 @@ function removeOldBackups(directory, prefix) {
} }
} }
function getImages(path) { /**
* Get a list of images in a directory.
* @param {string} directoryPath Path to the directory containing the images
* @param {'name' | 'date'} sortBy Sort images by name or date
* @returns {string[]} List of image file names
*/
function getImages(directoryPath, sortBy = 'name') {
function getSortFunction() {
switch (sortBy) {
case 'name':
return Intl.Collator().compare;
case 'date':
return (a, b) => fs.statSync(path.join(directoryPath, a)).mtimeMs - fs.statSync(path.join(directoryPath, b)).mtimeMs;
default:
return (_a, _b) => 0;
}
}
return fs return fs
.readdirSync(path) .readdirSync(directoryPath)
.filter(file => { .filter(file => {
const type = mime.lookup(file); const type = mime.lookup(file);
return type && type.startsWith('image/'); return type && type.startsWith('image/');
}) })
.sort(Intl.Collator().compare); .sort(getSortFunction());
} }
/** /**