fs.rename
is used to rename or move a file or directory in Node.js. It changes the name or location of a specified file or directory, moving it to a new path.
Key takeaways:
fs.rename
is asynchronous and non-blocking, letting other code execute while the rename operation happens in the background.
fs.renameSync
is synchronous and blocks further execution until the rename operation is complete.
Use fs.rename
for non-blocking tasks, such as renaming files in web applications while keeping the app responsive.
Use fs.renameSync
for blocking tasks, like sequential operations, where immediate renaming is crucial for subsequent steps.
Handle errors in fs.rename
using if-else conditions, and in fs.renameSync
using try-catch blocks.
Both methods use the same parameters: path
, existingName
, and newName
.
Import the fs
module to access and use these methods.
The fs
module is a built-in file system module in Node.js
that consists of several methods that can be used to access and manipulate files on the operating system. rename()
and renameSync()
are the fs
methods used to rename an existing directory.
The main difference between both methods is that rename()
is an asynchronous method and renameSync()
is a synchronous method.
Let’s look at their key differences and get a basic idea regarding when to use which method.
rename() | renameSync() | |
Asynchronous vs. Synchronous | It is asynchronous that means when this function is called, it renames the existing directory while the other code continues to execute. | It is synchronous that means when this function is called, it will execute and rename the existing directory and send a callback. Till then the system will go in waiting and nothing else is executed. |
Syntax | Use if–else to handle cases. | Use try–catch to handle cases. |
When to Use | Used when there is a need to handle non-blocking requests. Hence, no immediate need to rename the directory. | Used where there is a need for a blocking request to ensure the directory is renamed immediately. |
Real Life Example | We can rename directories asynchronously when using a web application that should stay responsive while the operation is occuring in the background. | We can rename directories synchronously when sequential execution is occuring. For example, if we want to create a file inside the renamed file. So, inorder to use its path sequential execution is required. |
Import the Node.js package fs
to access files:
const fs = require('fs')
The parameters for the fs.rename()
and fs.renameSync()
methods are the same, with a slight difference in syntax.
The syntax for fs.rename()
when handling its cases using if–else conditions.
const fs = require('fs');fs.rename('existingName', 'newName', (err) => {if (err) throw err;console.log('Directory renamed successfully!');});
The syntax for fs.renameSync()
when handling its cases using try–catch block.
const fs = require('fs');try {fs.renameSync('existingName', 'newName');console.log('Directory renamed successfully!');} catch (err) {console.error('Error renaming directory:', err);}
path:
The destination of the directory that is to be renamed.
existingName
: The already assigned name for the directory that we want to rename.
newName
: The new name assigned to the existing directory that we want to rename.
err:
A callback function that is called once the method is executed and returns one of the two cases:
error
: The method fails to rename the specified directory.
null
: The method successfully renames the specified directory.
This code renames dir1
directory inside the public
directory and then renames the public
directory. We have used both methods to communicate the difference between their implementation practically. Moreover, we have used a direct directory and a nested directory with a path to show how it is reached.
Let’s understand the output of the above example code and examine the difference in the behavior of a synchronous and asynchronous function.
Contents of the public
directory are printed and contains a dir1
directory.
Contents of the root
directory are printed, and it contains the public
directory.
renameSync()
method is executed first, and its success case statement is printed.
Contents of the root
directory are again printed to check if the rename()
method is executed or not, but no change is reflected.
Contents of the public
directory are again printed to check if the renameSync()
method’s changed since we already received a successful callback from it. Notice that the dir1
directory is renamed to dir1Latest
.
Contents of the root
directory are printed once again to check if the rename()
method executed once all the other existing code has been executed. Notice that the public
directory is renamed to publicLatest
.
The success case statement of the renameSync()
method is printed once all the other code has been executed and the directory name is successfully renamed.
A quick quiz to test your understanding.
What will happen if we rename the public
directory using the renameSync()
and dir1
directories using rename()
?
It will work fine.
It will throw an error.
In conclusion, the fs.rename()
and fs.renameSync()
methods in Node.js provide essential functionality for renaming files or directories. The key distinction lies in their execution styles:
fs.rename()
operates asynchronously, ensuring non-blocking execution suitable for responsive applications.
fs.renameSync()
works synchronously, ensuring blocking execution for sequential operations where immediate renaming is necessary.
By understanding these differences and the contexts in which each method is applicable, developers can choose the appropriate method to handle file system operations effectively.
Unlock your full potential with our comprehensive Node.js course. Dive deeper into the topic and gain hands-on experience through expert-led lessons:
Haven’t found what you were looking for? Contact Us
Free Resources