← coderrocketfuel.com

How to Rename a Directory in Node.js

How do you rename a directory or folder in a filesystem using Node.js?

Node.js has a built-in Fs core module that provides an fs.rename() and fs.renameSync() function that handles the renaming of files and directories.

In this article, we'll show you how to use both of those functions. They both serve the same purpose, but one is synchronous and the other is asynchronous. Therefore, the code will look slightly different for each method.

To get the code in this article to work, make sure you have Node.js installed on your local machine.

If you need one, we created a guide on installing Node.js.

Let's get started!

Table of Contents

Method 1 - fs.rename()

We'll go over the asynchronous fs.rename() version first.

The fs.rename() function takes two parameters: an old file path and a new file path. The old file path will be the current name of the directory we want to change and the new file path will be what we want to change it to.

Here's what the code looks like:

const fs = require("fs")

const currPath = "./my-directory"
const newPath = "./new-directory-name"

fs.rename(currPath, newPath, function(err) {
  if (err) {
    console.log(err)
  } else {
    console.log("Successfully renamed the directory.")
  }
})

The first thing we do is create the currPath and newPath variables. These represent the path to the directory we want to change and the new name we want to give the directory.

Then, we use the fs.rename() function and give it three parameters: the currPath variable, the newPath variable, and a callback function that returns an error if one occurs.

When you run the code, a success message will be logged. If an error occurred, the error message will be logged.

In the next section, we'll show you how to use the synchronous fs.renameSync() version of the method we just went through.

Method 2 - fs.renameSync()

The fs.renameSync() function is the synchronous version of fs.rename().

Both versions serve the same purpose and the fs.renameSync() function takes an old path and new path as parameters. But, this method will stop your code while it runs, so we need to structure our code slightly different than the previous example.

Here's what the code looks like:

const fs = require("fs")

const currPath = "./my-directory"
const newPath = "./new-directory-name"

try {
  fs.renameSync(currPath, newPath)
  console.log("Successfully renamed the directory.")
} catch(err) {
  console.log(err)
}

Like the previous example, we create two variables that hold our old and new directory paths.

But, we use a try...catch statement to handle our synchronous code. The catch section will stop the function and log an error if one occurs. And inside the try section, we call the fs.renameSync() function and log a success message when it finishes.