Skip to content

Instantly share code, notes, and snippets.

@paulodutra
Created November 22, 2021 16:05
Show Gist options
  • Save paulodutra/13224dedbb6b98afaa0e4211a4e09bb7 to your computer and use it in GitHub Desktop.
Save paulodutra/13224dedbb6b98afaa0e4211a4e09bb7 to your computer and use it in GitHub Desktop.
rename files in path specific node
const fs = require('fs').promises;
const fsSync = require('fs');
const path = require('path');
const REGEX_REPLACE =/([\u0300-\u036f]|[^0-9a-zA-Z])/g;
/**
* PATH: Constante a ser definida onde possui os arquivos.
*/
const PATH = 'path-to-files';
/**
* getFiles: Retorna uma lista com o path e nome dos arquivos presente no path informado
* @param {*} path
* @returns
*/
async function getFiles(path){
const files = await fs.readdir(path);
const pathFiles = [];
for(let file in files) {
pathFiles.push(`${PATH}/${files[file]}`);
}
return pathFiles;
}
/**
* getNewNameFile: Retorna uma nova string com o nome normalizado e o path do arquivo
* @param {*} oldPathName
* @returns
*/
function getNewNameFile(oldPathName){
const extension = path.extname(oldPathName);
const oldName = path.basename(oldPathName, extension);
const newName = oldName.normalize('NFD').replace(REGEX_REPLACE, '');
console.log('novo nome do arquivo:', newName);
return `${PATH}/${newName}${extension}`;
}
/**
* renameFile: Recebe o path com o nome do arquivo antigo e o path e o nome do arquivo novo
* e renomeia o mesmo.
* @param {*} oldName
* @param {*} newName
* @return void
*/
async function renameFile(oldName, newName){
fsSync.renameSync(oldName, newName);
}
/**
* main: Utiliza as funções descritas anteriormente
* @returns
*/
async function main(){
const files = await getFiles(PATH);
let oldName = '';
let newName = '';
for(file in files){
oldName = `${files[file]}`;
newName = await getNewNameFile(files[file]);
await renameFile(oldName, newName);
}
console.log('Arquivos renomeados com sucesso!');
return;
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment