Skip to content

Instantly share code, notes, and snippets.

@ngochangjelly
Last active June 7, 2022 16:13
Show Gist options
  • Save ngochangjelly/f3a76ff3b27ada4eafbaa4a8c05bb94c to your computer and use it in GitHub Desktop.
Save ngochangjelly/f3a76ff3b27ada4eafbaa4a8c05bb94c to your computer and use it in GitHub Desktop.
replace filename with a pattern in a folder for nodejs
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)}`)
}
});
});

HOW TO USE NODE SNIPPET

  • 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

Screenshot 2022-06-07 at 23 05 44

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment