У меня в папке скопилось много фото с названиями типа <день>,<месяц>,<год> (<порядковый номер>).jpg. И я решил что лучше будет переименовать их в <год>,<месяц>,<день>(<порядковый номер>).jpg, что бы когда открываешь папку не заморачиваться с упорядочиванием.

Переименовывать вручную не наш путь :) Набросал скрипт

'use strict';

const fsp = require('node:fs/promises');

const path = require('node:path');

const targetDir = '/your/directory/path';

const run = async (targetDir) => {

const files = await fsp.readdir(targetDir);

for (const file of files) {

if (file.startsWith(0) && file.includes(',')) {

const parsedFile = path.parse(file);

const [day, month, dirtyYear] = parsedFile.name.split(',');

const [year, seq] = dirtyYear.split(' ');

const newFileName = ${year}.${month}.${day}${seq};

const oldPath = path.join(targetDir, file);

const newPath = path.join(targetDir, newFileName);

await fsp.rename(oldPath, newPath);

}

}

};

run(targetDir).catch(console.error);

Прогнал этот скрипт ещё для разделителей в виде точки и тире.

Прошло не без косяков, появились файлы с названиями типа 2024(5).12.01undefined Правлю скрипт и радуюсь результату.

'use strict';

const fsp = require('node:fs/promises');

const path = require('node:path');

const targetDir = '/your/directory/path';

const run = async (targetDir) => {

const files = await fsp.readdir(targetDir);

for (const file of files) {

if (file.includes('undefined')) {

const newFileName = file.replace(

/(\d{4})((\d+)).(\d{2}).(\d{2})undefined/,

'$1.$3.$4($2)',

);

const oldPath = path.join(targetDir, file);

const newPath = path.join(targetDir, newFileName);

await fsp.rename(oldPath, newPath);

}

}

};

run(targetDir).catch(console.error);

Делая всё это вспомнил недавно прочитанную фразу: > Призвание инженера — изобретать штуку, которая решает проблему, которой ещё не существовало.

#pet #бекенд