Node.js comes with a built-in fs core module that provides fs.rename() and fs.renameSync() methods to handle the renaming of files and directories.

In this article, you'll learn how to use both these methods to rename a directory in a Node.js environment. They both do the same task — renaming files and folders, but the former is asynchronous and the latter is synchronous. Therefore, you may notice a slight difference in the code for each method.

fs.rename() Method

The fs.rename() method accepts two arguments, the current folder name you want to rename and the new folder name, and asynchronously perform the rename operation.

Here is an example:

const fs = require('fs');

// directory paths
const oldDirName = './images';
const newDirName = './img';

// rename the directory
fs.rename(oldDirName, newDirName, (err) => {
    if(err) {
        throw err;
    }

    console.log("Directory renamed successfully.");
});

fs.renameSync() Method

The fs.renameSync() method works similarly to the above method but it is synchronous. This means that it blocks the Node.js event loop execution until the rename operation is not completed.

Here is how the code looks like:

const fs = require('fs');

// directory paths
const oldDirName = './images';
const newDirName = './img';

// rename the directory
try {
    fs.renameSync(oldDirName, newDirName);

    console.log("Directory renamed successfully.");
    
} catch (err) {
    console.log(err);
}

Take a look at this guide to learn more about reading and writing files in a Node.js application.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also Subscribe to RSS Feed.

Last Updated: