How to Rename Multiple Files in a Folder Using Node.js (fs Module)

Robin
Updated on October 6, 2022

It is easy to rename multiple files inside a folder using the Node.js fs module. You can change all file names or specific types of files inside a folder.

There are 3 steps to rename all or multiple files in a folder with NodeJS:

  1. Get all file names from a folder using the fs.readdir() method.
  2. Loop through those names to access each of them individually.
  3. Change each file name inside the loop with the fs.rename() method.

You can change multiple file names following these 3 steps synchronously or asynchronously. If you know the differences between synchronous and asynchronous programming, I am sure that you will choose the asynchronous method.

But don't worry, I will show you both methods in this article. You will also see how to rename certain types of files in a folder.

Rename All Files in a Folder With Node.js Asynchronously

As you have seen earlier, you will need to use 2 methods from the fs module to get the job done. I will use the promised version of this module with the async/await syntax.

When we are changing the names of many files, it might take some time to complete. That's why it is good to do this asynchronously. This will not block the main thread.

          const path = require('path');
const fs = require('fs').promises;

const renameFiles = async (folderPath) => {
    try {
        const files = await fs.readdir(folderPath);

        for (const file of files) {
            const fileInfo = path.parse(file);

            const oldPath = path.join(__dirname, folderPath, file);
            const newPath = path.join(__dirname, folderPath, `${fileInfo.name}-'add_something'${fileInfo.ext}`);

            await fs.rename(oldPath, newPath);
        }
    } catch (error) {
        // Handle error here
        console.log(error);
    }
};

renameFiles('./img');

        

To use the promised version of the fs module, you have to require it. I am creating a renameFiles() function that accepts a folder path. Because I will use the async/await syntax to handle the promise.

In step 1, I am getting all the file names from the given folder path using the fs.readdir() method.

In step 2, I am looping over the array of files with the for...of statement in JavaScript. Inside this statement, you will have access to each file name.

In step 3, I will change the file name individually using the fs.rename() method. But before that, you need to construct 2 paths for the file.

Because the fs.rename() method needs the old path where the existing file lives as its first parameter. In the second parameter, this method will take the new path where the file will go after changing the name.

I am using the path.parse() method to get the file extension and the existing file name. You can access the name and extension from fileInfo.name and fileInfo.ext properties respectively.

You can add anything before or after the existing file name to generate a new name. Then add the file extension at the end of the new file name.

When you pass these old and new file paths in the fs.rename() method, it will change those file names.

If you don't want to use the promised version of the fs module, you can get the same result with the callback functions.

          const path = require('path');
const fs = require('fs');

const folderPath = './img';

fs.readdir(folderPath, (error, files) => {
    if (error) {
        // Handle error here
        console.log(error);
    }

    for (const file of files) {
        const fileInfo = path.parse(file);

        const oldPath = path.join(__dirname, folderPath, file);
        const newPath = path.join(__dirname, folderPath, `${fileInfo.name}-'add_something'${fileInfo.ext}`);

        fs.rename(oldPath, newPath, (error) => {
            if (error) {
                // Handle error here
                console.log(error);
            } else {
                console.log('File names changed successfully');
            }
        });
    }
});
        

Here, without using the promise and async/await syntax, I am using callback functions with those methods. It will give you the same result because you have to use the same 3 steps.

If you like the promised version, you can use that. Otherwise, you can choose the callback syntax. It's completely up to you.

Also Read: How to Get All Files in Directories (Recursively) with Node.js

Rename All Files in a Folder Using Node.js Synchronously

Sometimes you might need to change all file names in a folder synchronously with the Node.js fs module. You can also use those methods synchronously.

It is not recommended to do it using synchronous methods. Because they will block the main thread. JavaScript will stop executing other code until the renaming process completes.

          const path = require('path');
const fs = require('fs');

const folderPath = './img';

try {
    const files = fs.readdirSync(folderPath);

    for (const file of files) {
        const fileInfo = path.parse(file);

        const oldPath = path.join(__dirname, folderPath, file);
        const newPath = path.join(__dirname, folderPath, `${fileInfo.name}-'add_something'${fileInfo.ext}`);

        fs.renameSync(oldPath, newPath);
    }
} catch (error) {
    // Handle error here
    console.log(error);
}
        

You have to follow the same steps as you have seen in the previous section. The main difference is that you will use the fs.readdirSync() method to get all the file names.

You need to change a file name with the fs.renameSync() method. Other than that, there are no differences in those steps.

Rename Specific Types of Files in a Folder Using Node.js

A folder might contain different types of files. You can rename specific types of files in a folder without changing all files.

You can use any technique shown in the previous section. Just before changing the names with fs.rename() method, you have to check the file extension.

          const path = require('path');
const fs = require('fs').promises;

const renameFiles = async (folderPath, fileType) => {
    try {
        const files = await fs.readdir(folderPath);

        for (const file of files) {
            const fileInfo = path.parse(file);

            const oldPath = path.join(__dirname, folderPath, file);
            const newPath = path.join(__dirname, folderPath, `${fileInfo.name}-'add_something'${fileInfo.ext}`);

            if (fileInfo.ext === fileType) {
                await fs.rename(oldPath, newPath);
            }
        }
    } catch (error) {
        // Handle error here
        console.log(error);
    }
};

renameFiles('./img', '.jpg');

        

I am using the promise and async/await syntax that we discussed in the first section. But in this example, I am taking the second parameter for a file type.

Here I will provide the type of file that I want to rename. I am also using a if check inside the for...of statement. With this check, it will only change the file name whose extension matches the file type.

That's it. In this way, you can rename certain types of files inside a folder.

Also Read: How to Find Files By Extension, Name, or Pattern in Node.js

Conclusion

It is not that difficult to apply particular methods in different ways to get different results. You can change file names synchronously using some methods from the fs module.

But by changing the method names, you can do the same thing asynchronously. With those methods just modifying a few things, you can rename specific types of files in NodeJS.

This is the most interesting part of programming. We can learn one thing and use it in many places.

By following this article, you have learned how to rename all or multiple files in a folder with the Node.js fs module. You have also seen a way to change the names of certain file types.

Related Posts