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.