Skip to content

Instantly share code, notes, and snippets.

@ishowshao
Last active July 2, 2023 13:46
Show Gist options
  • Save ishowshao/9579a23e83d8c1fc17190b5619ea991f to your computer and use it in GitHub Desktop.
Save ishowshao/9579a23e83d8c1fc17190b5619ea991f to your computer and use it in GitHub Desktop.
rename all files in the folder to the file creation time
// The frame is written by GPT, and I perfect the details
const fs = require("fs");
const path = require("path");
const dayjs = require('dayjs');
const folderPath = "path/to/folder";
fs.readdir(folderPath, (err, files) => {
if (err) {
console.error(err);
return;
}
files.forEach((file) => {
const oldFilePath = path.join(folderPath, file);
const stats = fs.statSync(oldFilePath);
const createTime = stats.birthtime;
const d = dayjs(createTime);
const formattedTime = d.format('YYYYMMDDHHmmss');
const fileName = path.parse(file).name;
const fileExtension = path.parse(file).ext;
const newFileName = `${formattedTime}`;
const newFilePath = path.join(
folderPath,
`${newFileName}${fileExtension.toLowerCase()}`
);
fs.renameSync(oldFilePath, newFilePath);
console.log(`Renamed ${file} to ${newFileName}${fileExtension.toLowerCase()}`);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment