Renaming files from a folder sequentially - Javascript

Asked

Viewed 874 times

0

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

Example:

Of

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

To

imagem01.jpg | imagem02.jpg | imagem03.jpg

Does anyone know of a library/code/extension (JS/Jquery) that allows me to do this ?

  • Try to use node.js as described in that post by the international community

  • angularjs it certainly does not serve for this, with js via browser, I think it is not possible, but you can upload the photos and download them with a different name, but would go to the folder configured in the browser (usually, downloads) and would not delete the original files

1 answer

1


You can use the node.js as Leonardo mentioned.

  • Request the library file-system.

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

    // 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 that, use the function forEach() 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 function copyFile() to copy the files to another directory (remember that the function copyFile() does not create new directories, for this you need to use the function mkdir().

    // 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})
        })
    })
    
  • However, in this way, the fs will create a file without extension, so you must capture the extension of that file in order to copy it in the correct way.

    // 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 helped c:

Browser other questions tagged

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