Created
November 8, 2020 13:51
-
-
Save MaximStone/8a2fb2392d37fb40d5d6de486c0fc384 to your computer and use it in GitHub Desktop.
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 targetDir = 'D:\\FTP\\'; | |
const patternToExcludeInName = 'text_to_delete_in_name_of_dir_or_file'; | |
const fileNameToDeletePattern = 'file_to_delete_if_found' | |
const walkSync = function (dir, filelist) { | |
var files = fs.readdirSync(dir, {withFileTypes: true}); | |
filelist = filelist || []; | |
files.forEach(function (file) { | |
if (fs.statSync(path.join(dir, file.name)).isDirectory()) { | |
filelist = walkSync(path.join(dir, file.name), filelist); | |
} else { | |
filelist.push(path.join(dir, file.name)); | |
} | |
}); | |
return filelist; | |
}; | |
const getDirectories = srcPath => fs.readdirSync(srcPath).filter(file => fs.statSync(path.join(srcPath, file)).isDirectory()); | |
const renameDirs = function (dpath) { | |
const newDirs = getDirectories(dpath); | |
newDirs.forEach(async pathElement => { | |
if (pathElement.indexOf(patternToExcludeInName) != -1) { | |
await fs.promises.rename(path.join(dpath, pathElement), path.join(dpath, pathElement.replace(patternToExcludeInName, ''))); | |
} | |
await renameDirs(path.join(dpath, pathElement)); | |
}); | |
} | |
renameDirs(targetDir); | |
const allFiles = walkSync(targetDir); | |
allFiles.forEach(async filePath => { | |
if (filePath.indexOf(patternToExcludeInName) != -1) { | |
await fs.promises.rename(filePath, filePath.replace(patternToExcludeInName, '')); | |
} | |
if (filePath.indexOf(fileNameToDeletePattern) != -1) { | |
await fs.promises.unlink(filePath); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment