# How to rename a directory in Node.js

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Apr 11, 2020, updated Aug 27, 2022. Topics: Node.js.
Canonical URL: https://attacomsian.com/blog/nodejs-rename-directory

> A short article to learn how to quickly rename a folder in a Node.js application.

Node.js comes with a built-in `fs` 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 these methods to rename a directory in a Node.js environment. They both do the same task &mdash; 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 renames the folder.

Here is an example:

```javascript
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.')
})
```

Alternatively, you can use the promise-based `fsPromises.rename()` method:

```javascript
const fsPromises = require('fs/promises')

const renameFileAsync = async () => {
  try {
    const oldDirName = './images'
    const newDirName = './img'

    await fsPromises.rename(oldDirName, newDirName)

    console.log('Directory renamed successfully.')
  } catch (err) {
    console.error(err)
  }
}

renameFileAsync()
```

## `fs.renameSync()` Method

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

```javascript
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)
}
```

Read [this guide](https://attacomsian.com/blog/reading-writing-files-nodejs) to learn more about reading and writing files in a Node.js application.
