Skip to content

Instantly share code, notes, and snippets.

@AyemunHossain
Created September 14, 2023 05:25
Show Gist options
  • Save AyemunHossain/326f37f95577f3759c21dc026883121a to your computer and use it in GitHub Desktop.
Save AyemunHossain/326f37f95577f3759c21dc026883121a to your computer and use it in GitHub Desktop.
Change file name in Nodejs
const fs = require('fs');
const path = require('path');
const directoryPath = __dirname;
// Read the contents of the directory
fs.readdir(directoryPath, (err, files) => {
if (err) {
console.error('Error reading directory:', err);
return;
}
// Filter the files to include only .png files
const pngFiles = files.filter((file) => path.extname(file).toLowerCase() === '.png');
// Rename each .png file
pngFiles.forEach((file) => {
const oldFilePath = path.join(directoryPath, file);
const fileShortName = file.split('.')[0];
const newFileName = "new_name" + '.png'; ///Specify the new name here
const newFilePath = path.join(directoryPath, newFileName);
fs.rename(oldFilePath, newFilePath, (renameErr) => {
if (renameErr) {
console.error(`Error renaming ${file}:`, renameErr);
} else {
console.log(`${file} renamed to ${newFileName}`);
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment