Created
September 14, 2023 05:25
-
-
Save AyemunHossain/326f37f95577f3759c21dc026883121a to your computer and use it in GitHub Desktop.
Change file name in Nodejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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