How to rename a directory in Node.js

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 — 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:

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:

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.

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 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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.