-
Clone this gist and store in your computer
-
Make sure you have installed Nodejs: https://nodejs.org/en/
-
Open terminal and type this:
node ~/changeFileName.js 'Downloads/test' 'file' 'newFile'
-
command explaination
-
changeFileName.js is the name of this code snippet
-
argument 2 is 'Downloads/test' - the folder which contains file that you want to rename
-
'file': old name pattern
-
'newFile': new name pattern
Last active
June 7, 2022 16:13
-
-
Save ngochangjelly/f3a76ff3b27ada4eafbaa4a8c05bb94c to your computer and use it in GitHub Desktop.
replace filename with a pattern in a folder for 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 { promisify } = require('util'); | |
const { argv } = require('process') | |
const fs = require('fs'); | |
const path = require('path'); | |
const folder = argv[2] | |
const oldPattern = argv[3] | |
const newPattern = argv[4] | |
const directoryPath = path.join(__dirname, folder); | |
if (!folder || !fs.existsSync(directoryPath)) { | |
console.error('Directory does not exist') | |
return | |
} | |
const renameFileAsync = promisify(fs.rename); | |
fs.readdir(directoryPath, function (err, files) { | |
if (err) { | |
return console.log('Unable to scan directory: ' + err); | |
} | |
files.forEach(function (file) { | |
if (file.includes(oldPattern)) { | |
const oldFilePath = directoryPath + '/' + file | |
const newName = file.replace(oldPattern, newPattern) | |
const newFilePath = directoryPath + '/' + newName | |
renameFileAsync(oldFilePath, newFilePath) | |
console.log(`success rename file ${file} into ${file.replace(oldPattern, newPattern)}`) | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment