Rename files to include a prefix

Asked

Viewed 28 times

-1

I need to rescue some files with any name (Ex: "João") and rename them including a prefix ("RJ-João").

I managed to list but I’m not able to rename the files:

const testFolder = './teste/';
const fs = require('fs');

fs.readdir(testFolder, (err, files) => {
  var arquivos = files.forEach(file => {
 
     console.log( files );
    
  });

2 answers

0


You can do it this way:

const testFolder = './teste/';
const fs = require('fs');

const files = fs.readdirSync(testFolder);
const prefix = 'prefix'
files.forEach((file) => {
  fs.renameSync(`${testFolder}${file}`, `${testFolder}${prefix}${file}`)
});
  • I recommend that you explain why your solution (or how the code works) when answering a question to help understand who originally published the post.

0

Thank you very much.

Follow the final code.

const testeFolder = './test/'; // pasta de busca
const fs = require('fs');

const files = fs.readdirSync(testeFolder);  //lista todos os arquivos na pasta
var prefix = 'Teste - '; //prefixo
files.forEach((file)=>{
  fs.renameSync(`${testeFolder}${file}`, `${testeFolder}${prefix}${file}`) // pega o item com o nome antigo e coloca o prefixo

  // Remover o Prefixo

  //var remove = (file.replace("Teste - ", " ")); //busca a palavra

  //console.log(remove);
 //fs.renameSync(`${testeFolder}${file}`, `${testeFolder}${remove}`) // pega o item com o nome antigo e remove o prefixo
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.