Skip to content

Instantly share code, notes, and snippets.

@usagizmo
Last active October 14, 2023 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save usagizmo/5adf7de2cfd02d8e99b9b88f8dac1fff to your computer and use it in GitHub Desktop.
Save usagizmo/5adf7de2cfd02d8e99b9b88f8dac1fff to your computer and use it in GitHub Desktop.
[動画/写真] メタ情報から DateTimeOriginal/作成日/更新日 の指定とファイル名の変更
import { execSync } from 'child_process';
import fs from 'node:fs/promises';
import _fs from 'fs';
import path from 'path';
import { parse, isBefore, format, isValid } from 'date-fns';
const directoryPath = __dirname + '/files';
const files = await fs.readdir(directoryPath);
const datePatterns = ["CreateDate", "CreationDate", "ContentCreateDate", "DateTimeOriginal"];
files.forEach((file) => {
const filePath = path.join(directoryPath, file);
const fileExtension = path.extname(filePath).toLowerCase();
try {
const stdout = execSync(`exiftool -s "${filePath}" | grep Date`).toString();
const dates: { pattern: string, date: Date }[] = [];
datePatterns.forEach(pattern => {
const match = stdout.match(new RegExp(`${pattern}\\s+:\\s+(.+)`));
if (match && match[1]) {
let date = parse(match[1], "yyyy:MM:dd HH:mm:ss", new Date())
if (!isValid(date)) {
date = parse(match[1], "yyyy:MM:dd HH:mm:ssxxx", new Date())
}
isValid(date) && dates.push({ pattern, date })
}
});
if (dates.length > 0) {
const oldestDate = dates.reduce((oldest, currentDate) => isBefore(currentDate.date, oldest.date) ? currentDate : oldest);
execSync(`exiftool -overwrite_original "-AllDates<${oldestDate.pattern}" "${filePath}"`);
let newFileName = `DS_${format(oldestDate.date, 'yyyyMMdd_HHmmss')}${fileExtension}`;
let newFilePath = path.join(directoryPath, newFileName);
let counter = 2;
while (_fs.existsSync(newFilePath)) {
newFileName = `DS_${format(oldestDate.date, 'yyyyMMdd_HHmmss')}_${counter}${fileExtension}`;
newFilePath = path.join(directoryPath, newFileName);
counter++;
}
execSync(`mv "${filePath}" "${newFilePath}"`);
const touchDate = format(oldestDate.date, "yyyyMMddHHmm.ss");
execSync(`touch -t ${touchDate} "${newFilePath}"`);
console.log(`Updated ${file} to ${newFileName}`);
} else {
console.log(`No matching date patterns found for ${file}`);
}
} catch (error) {
console.error(`Error processing ${file}:`, error);
}
});
{
"name": "format-photos",
"version": "1.0.0",
"author": "usagizmo",
"dependencies": {
"date-fns": "^2.30.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment