diff --git a/src/endpoints/images.js b/src/endpoints/images.js index a01e34073..7290307ca 100644 --- a/src/endpoints/images.js +++ b/src/endpoints/images.js @@ -82,7 +82,7 @@ router.post('/list/:folder', (request, response) => { } try { - const images = getImages(directoryPath); + const images = getImages(directoryPath, 'date'); return response.send(images); } catch (error) { console.error(error); diff --git a/src/util.js b/src/util.js index b82007156..9f42afb13 100644 --- a/src/util.js +++ b/src/util.js @@ -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 - .readdirSync(path) + .readdirSync(directoryPath) .filter(file => { const type = mime.lookup(file); return type && type.startsWith('image/'); }) - .sort(Intl.Collator().compare); + .sort(getSortFunction()); } /**