Rename files in a folder in a sequential way - JavaScript

0

How would you be able to rename files of the same format but with different names (for example: Images) to a sequential pattern?

Example:

From

titulo-capa.jpg | foto-perfil.jpg | background.jpg

To

imagem01.jpg | imagem02.jpg | imagem03.jpg

Does anyone know of any library / code / extension (JS / JQuery) that would allow me to do this?

    
asked by anonymous 08.08.2018 / 19:31

1 answer

1

You can use node.js as Leonardo mentioned.

  • Requires the file-system library.

    const fs = require("fs")
    
  • Next, you can get an array with the name and extension of all files in a directory using the readdir() function.

    // Como usar a função
    fs.readdir(path,callback)
    
    // isso vai retornar todos os arquivos do diretório raíz
    fs.readdir("./",(err,files)=>{
        console.log(files)
    })
    
  • After this, use the forEach() function in the array to perform an action on each file.

    // Como usar a função
    array.forEach(function(element,index,array))
    
    // Código
    fs.readdir("./raw_images",(err,files)=>{
        files.forEach((file,index)=>{
    
        })
    })
    
  • Use the copyFile() function to copy the files to another directory (remember that the copyFile() function does not create new directories, so you need to use the mkdir() function.

    // Como usar a função
    fs.copyFile(src,dest)
    
    // Código
    fs.readdir("./raw_images",(err,files)=>{
        files.forEach((file,index)=>{
            fs.copyFile('./raw_images/${file}','./raw_images/new_images/imagem${index})
        })
    })
    
  • But in this way, fs will create a file without extension, so you should capture the extension of this file in order to copy it correctly.

    // Gera um novo array onde o . é o critério para separar os valores ("meu-arquivo.jpeg" vai se tornar ["meu-arquivo","jpeg"]
    var extension = file.split(".")
    // Salva apenas o último elemento do array
    extension = extension[extension.length-1]
    
  • The code will look something like this:

    fs.readdir("./raw_images",(err,files)=>{
        files.forEach((file,index)=>{
            var extension = file.split(".")
            extension = extension[extension.length-1]
    
            fs.copyFile('./raw_images/${file}','./raw_images/new_images/imagem${index}.${extension}')
    
        })
    
    })
    

I hope I have helped c:

    
09.08.2018 / 04:46