3 Methods to Rename a File Using Node.js fs Module (Explained)

Robin
Updated on September 13, 2022

We often need to rename a file in a Node.js server while working with files. Node.js has a built-in module that can help you do that. You can change the name of any type of file.

Node.js fs module has the fs.rename() method to change the file name asynchronously and fs.renameSync() method to rename a file synchronously. Both methods accept the path of the old file that will change and the path of the new file to store it after the change.

In situations like downloading files from a Node.js server or uploading files to the server, we change the file name using this module to give unique names to the files. There are many other situations where we need to modify the name of a file.

Therefore it is important to know how to use these two methods properly. After this lesson, you will be able to rename any type of file using the Node.js fs module.

How to Rename a File Using fs Module in Node.js

We will discuss 3 techniques in this lesson to change a file name. You will understand which technique you should use in your project after reading this article.

As we will use the fs.rename() and fs.renameSync() in this post, let's see the syntax of these methods.

Syntax of fs.rename()

          fs.rename(old_file_path, new_file_path, callback_function);
        

Syntax of fs.renameSync()

          fs.renameSync(old_file_path, new_file_path);
        

As you can see, both methods have 2 common parameters. The fs.rename() has an additional parameter because it works asynchronously.

  • old_file_path – It is a string. In this parameter, we define the path of the file including the name we want to change.
  • new_file_path - It is a string. We provide the new file path and the new name that we want to assign.

The callback function runs automatically after the fs.rename() method is executed. This function gives the error object if there is any or you can perform something else after changing the name.

Let's discuss those 3 techniques to rename a file and learn which is the best to use.

3 Methods to Rename a File Using Node.js fs Module (Explained)

Method 1: Rename a File Asynchronously With Callback

When we perform something asynchronously in JavaScript that means, we are doing something without blocking the main thread of JavaScript. This is one of the main differences between synchronous and asynchronous programming.

When we don't block the main thread in JavaScript, our application will be able to perform multiple things at the same time. That is why the callback function is used.

          const fs = require('fs');

fs.rename('./files/old.js', './files/new.js', (error) => {
    if (error) {
        // handle error here

        console.log(error);
        return;
    }

    console.log('Rename completed successfully');
});
        

I have a files folder and inside this folder, there is an "old.js" file. I want to change the name to "new.js" using NodeJS.

I am calling the fs.rename() from the fs module. This method needs a full path of the old and new files. In the callback function, I have the error object as its parameter.

I can check the error and handle it inside the function. If there is no error then it will be null. In this case, the method is executed successfully and the name has changed.

You can change the name of a single file this way. But You can also get all files from a folder recursively and rename all files in a folder using the Node.js fs module.

Method 2: Change File Name Asynchronously With Promise

You have seen how to use a callback function to rename a file but sometimes a callback function can create problems. Especially, if you have nested callback functions then it is called the "Callback Hell".

As the name suggests, it becomes very painful to work and manage our code in a large project. To make things easy and write clean code, we use promise and async/await syntax.

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

(async () => {
    try {
        await fs.rename('./files/old.js', './files/new.js');

        console.log('Rename completed successfully');
    } catch (error) {
        console.log(error);
    }
})();
        

In this example, I am using the fs.rename() method like the previous one. But I am getting the promised version of this method from the fs module.

It accepts 2 parameters this time. When we call this method, it will return a promise. For the async/await syntax, I am using a self-invoking function in JavaScript so that when I execute the file Using NodeJS, this function runs automatically.

But you can also use a regular function if you want. You need to use the try...catch statement to handle the errors.

When the function executes, it changes the name from "old.js" to "new.js" in the files folder.

Method 3: Use fs.renameSync() to Rename a File Synchronously

If you need to change a file name synchronously, you have to use the fs.renameSync() method from the fs module. But you need to keep in mind that, when you use this method, it will block the main thread of JavaScript.

The code you write after this method will not run until the execution of this method completes. It might slow down your application.

Now let's see how we can use the fs.renameSync() method in order to rename a file in a Node.js application.

          const fs = require('fs');

try {
    fs.renameSync('./files/old.js', './files/new.js');

    console.log('Rename completed successfully');
} catch (error) {
    // handle error here

    console.log(error);
};
        

It is very simple to use. You can call the fs.renameSync() method from the fs module. It takes 2 parameters i.e. the old file path and the new file path.

To handle the error, We need to use the try...catch statement in JavaScript.

Which Method Should You Choose?

Among these 3 techniques, I always prefer to use the fs.rename() method over the fs.renameSync() method. Because of the advantages of using asynchronous programming.

Between the callback and promise, It is good to use the promise syntax. Because it is easy to read and manage. That's why I use the fs.rename() method with the promise and async/await syntax.

But it's up to you which method you want to use in your application. You can choose any of them according to your requirements.

Conclusion

As you have seen, it is very easy to change a file name using the Node.js fs module. It gives you fs.rename() and fs.renameSync() methods to use. You can apply those methods in many ways.

I have shown you 3 techniques in this lesson. You also know the advantages and disadvantages of those techniques so that you can choose one of them.

I hope you have learned how to rename a file using the fs module in a Node.js server.

Related Posts